【发布时间】:2011-10-17 08:17:35
【问题描述】:
我正在尝试将 JSON 字符串转换为简单的 java 对象,但它返回 null。以下是课程详情。
JSON 字符串:
{"menu":
{"id": "file",
"value": "File",
}
}
这是可解析的类:
public static void main(String[] args) {
try {
Reader r = new
InputStreamReader(TestGson.class.getResourceAsStream("testdata.json"), "UTF-8");
String s = Helper.readAll(r);
Gson gson = new Gson();
Menu m = gson.fromJson(s, Menu.class);
System.out.println(m.getId());
System.out.println(m.getValue());
} catch (IOException e) {
e.printStackTrace();
}
}
以下是模型类:
public class Menu {
String id;
String value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String toString() {
return String.format("id: %s, value: %d", id, value);
}
}
每次我得到空值。谁能帮帮我?
【问题讨论】:
-
尝试让默认的 counstructor 确定它是否有效
-
检查这个以获得帮助。 stackoverflow.com/questions/6079505/…