我想将JSON字符串转换为简单的java对象,但它返回null。以下是课程详情。使用Gson将JSON转换为Java对象
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确定,告诉它是否工作 – PedroAGSantos
检查此寻求帮助。 http://stackoverflow.com/questions/6079505/converting-json-string-to-java-object –