[英]JSON inner field parsing with GSON
I am new to JSON and I love how incredibly potent and straight-forward GSON Api can be, compared to any other parsing methods I've researched. 我是JSON新手,与我研究过的任何其他解析方法相比,我都喜欢GSON Api的强大和直截了当。
I want to parse a rather complex JSON(using GSON) that resembles the following one in terms of structure: 我想解析一个相当复杂的JSON(使用GSON),该JSON在结构上类似于以下内容:
[
{
"name": "Steve",
"age": 42,
"description": null,
"email1": "steve@example.com",
"email2": null,
"address1": {
"type": "home",
"shippingMethod": "Charge by quantity",
"street": "Sunrise Ave",
"streetNo": 17
},
"address2": {
"type": "office",
"shippingMethod": null,
"street": "Sunset Ave",
"streetNo": 71
},
"anotherField": "another value"
},
{
"name": "Johnny",
...
"anotherField": "some other value"
}
]
I can see that I need to wrap it up with an array of Client objects, because my JSON starts with a "[" and I can also see I need another container class for the inner fields address1 and address2. 我可以看到我需要用一个Client对象数组将其包装起来,因为我的JSON以“ [”开头,而且我还可以看到内部字段address1和address2需要另一个容器类。 This is the container I came up with:
这是我想出的容器:
public class Client {
String name;
int age;
String description;
String email1;
String email2;
ClientAddress address1;
ClientAddress address2;
String anotherfield;
..
getters() and setters()
public class ClientAddress {
String type;
String shippingMethod;
String street;
int streetNo;
..
getters() and setters()
}
}
The instruction I wrote to grab the data and populate the wrapper fields is: 我写的获取数据并填充包装器字段的指令是:
Client[] clientsArray= (new Gson()).fromJson(jsonClients, Client[].class);
The result is only partially satisfying; 结果只是部分令人满意; I managed to access all the primitive fields (such as name,email1..), but the address1 and address2 fields are both null.
我设法访问了所有原始字段(例如name,email1 ..),但是address1和address2字段均为null。 As a result,
结果是,
clientsArray[i].getAddress1().getShippingMethod();
returns a null String. 返回一个空字符串。
Where did I go wrong? 我哪里做错了?
Is there a particular way of creating the classes that I am missing? 是否有创建我所缺少的类的特定方法?
Note: My JSON object is perfectly valid from a structure standpoint of view. 注意:从结构的角度来看,我的JSON对象是完全有效的。 If you see any errors, it's probably because they slipped when I was manually creating the above dummy/demo.
如果您看到任何错误,那可能是因为当我手动创建上述虚拟/演示时,它们发生了滑动。
Just to follow GSON Collections good practices , try changing 只是为了遵循GSON Collections的良好做法 ,请尝试更改
Client[] clientsArray= (new Gson()).fromJson(jsonClients, Client[].class);
to 至
Type collectionType = new TypeToken<List<Client>>(){}.getType();
List<Client> clientsArray = (new Gson()).fromJson(jsonClients, collectionType);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.