Java Gson-从json字符串转换为对象列表
我有一个JSON字符串,格式如下:Java Gson-从json字符串转换为对象列表,java,gson,Java,Gson,我有一个JSON字符串,格式如下: resp = '{"result": [{x: 1, y:2}, {x:3, y:4}]}' 我想将数据从“结果”键转换为对象列表。比如: List<MyCustomObj> data = new Gson() .fromJson(resp, new TypeToken<ArrayList<MyCustomObj>>(){}.getType()); List data=new Gson
resp = '{"result": [{x: 1, y:2}, {x:3, y:4}]}'
我想将数据从“结果”键转换为对象列表。比如:
List<MyCustomObj> data = new Gson()
.fromJson(resp, new TypeToken<ArrayList<MyCustomObj>>(){}.getType());
List data=new Gson()
.fromJson(resp,new-TypeToken(){}.getType());
有没有一种方法可以在上面的语句中指定从键“result”中提取?只需创建一个描述JSON结构的DTO,如:
@Getter @Setter
public class Response {
@Getter @Setter
public static class MyCustomObject {
private int x;
private int y;
}
private List<MyCustomObject> result;
}
@Getter@Setter
公众课堂反应{
@Getter@Setter
公共静态类MyCustomObject{
私人INTX;
私营企业;
}
私有列表结果;
}
那么它只是:
Response resp = gson.fromJson(json, Response.class);
List<MyCustomObject> result = resp.getResult();
Response resp=gson.fromJson(json,Response.class);
List result=resp.getResult();
保持JSON格式和数据结构同步,而不是进行一些特殊的解析,这可能是一个好主意。可能不会获得任何性能提升