Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Gson-从json字符串转换为对象列表_Java_Gson - Fatal编程技术网

Java Gson-从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

我有一个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()
.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格式和数据结构同步,而不是进行一些特殊的解析,这可能是一个好主意。可能不会获得任何性能提升