Gson - 从 json 字符串转换为对象列表

Gson - Convert from json string to list of objects

我有一个 JSON 格式的字符串:

resp = '{"result": [{x: 1, y:2}, {x:3, y:4}]}'

我想将数据从“结果”键转换为对象列表。类似于:

List<MyCustomObj> data = new Gson()
        .fromJson(resp, new TypeToken<ArrayList<MyCustomObj>>(){}.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;
}    

那么就是:

Response resp = gson.fromJson(json, Response.class);
List<MyCustomObject> result = resp.getResult();

保持 JSON 格式和数据结构同步而不是一些特殊的解析可能是个好主意。可能不会获得任何性能提升。