Java - 嵌套在嵌套中的 Gson 解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4453006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Gson parsing nested within nested
提问by BalusC
I have to interact with an API, and the response format (from what I've read) seems to be poorly structured. I've found a google groups reply to a somewhat similiar problem here, but I'm having trouble implementing a Response class to handle the Gson.fromJson. Is there an example I'm missing that's out there?
我必须与 API 交互,并且响应格式(根据我阅读的内容)似乎结构不佳。我发现一个谷歌集团回复有点类似的问题在这里,但我无法实现响应类来处理Gson.fromJson。有没有我遗漏的例子?
{
"response":{
"reference": 1023,
"data":{
"user":{
"id":"210",
"firstName":"john",
"lastName":"smith",
"email":"[email protected]",
"phone":"",
"linkedid":{
"id":"238"
}
}
}
}
}
回答by BalusC
The JSON objects {}
can be represented by a Map<String, Object>
or a Javabean class. Here's an example which uses a Javabean.
JSON 对象{}
可以由Map<String, Object>
或 Javabean 类表示。这是一个使用 Javabean 的示例。
public class ResponseData {
private Response response;
// +getter+setter
public static class Response {
private int reference;
private Data data;
// +getters+setters
}
public static class Data {
private User user;
// +getter+setter
}
public static class User {
private String id;
private String firstName;
private String lastName;
private String email;
private String phone;
private Linkedid linkedid;
// +getters+setters
}
public static class Linkedid {
private String id;
// +getter+setter
}
}
Use it as follows:
使用方法如下:
ResponseData responseData = new Gson().fromJson(json, ResponseData.class);