我很难理解GSON是否可以默认处理这种json,或者我是否需要为每个子元素实现反序列化器。
输入<<p> json/strong>{
"services":[
{
"id": 2,
"name": "Buy"
},
{
"id": 3,
"name": "Sell"
}
]
"status": {
"code": 0,
"message": ""
}
}
对我来说最好的结果是让下面的类包含所有的数据
java [POJO]
public class Services {
public List<ServiceItem> services;
public Status status;
public class ServiceItem {
public int id;
public String name;
}
public class Status {
public int code;
public String message;
}
}
是否有可能让GSON类和json,只是让它工作?或者我需要为每个子类创建反序列化器吗?
按如下方式更正json输入(您在status
字段前忘记了逗号)
{
"services":[
{
"id": 2,
"name": "Buy"
},
{
"id": 3,
"name": "Sell"
}
],
"status": {
"code": 0,
"message": ""
}
}
那么让我们考虑你的类如下
public class Services {
public List<ServiceItem> services;
public Status status;
// getters and setters
@Override
public String toString() {
return "["+services.toString()+status.toString()+"]";
}
public class ServiceItem {
public int id;
public String name;
// getters and setters
@Override
public String toString() {
return "("+id+","+name+")";
}
}
public class Status {
public int code;
public String message;
// getters and setters
@Override
public String toString() {
return ",("+code+","+message+")";
}
}
}
如果输入是文件jsonInput.json
,则
Gson gson = new Gson();
Services data = gson.fromJson(new BufferedReader(new FileReader(
"jsonInput.json")), new TypeToken<Services>() {
}.getType());
System.out.println(data);
如果输入是一个json字符串jsonInput
,那么
Gson gson = new Gson();
Services data = gson.fromJson(jsonInput, Services.class);
System.out.println(data);
输出:[[(2,Buy), (3,Sell)],(0,)]