gpt4 book ai didi

java - 使用 GSON 解析 JSON 内部字段

转载 作者:行者123 更新时间:2023-12-01 11:17:47 26 4
gpt4 key购买 nike

我是 JSON 新手,与我研究过的任何其他解析方法相比,我喜欢 GSON Api 的强大和直接性。
我想解析一个相当复杂的 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"
}
]

我可以看到我需要用 Client 对象数组将其包装起来,因为我的 JSON 以“[”开头,而且我还可以看到我需要另一个容器类来存储内部字段 address1 和 address2。这是我想出的容器:

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()
}
}

我编写的用于获取数据并填充包装器字段的指令是:

Client[] clientsArray= (new Gson()).fromJson(jsonClients, Client[].class);

结果只是部分令人满意;我设法访问所有原始字段(例如名称,电子邮件1..),但地址1和地址2字段均为空。结果,

clientsArray[i].getAddress1().getShippingMethod();

返回空字符串。

我哪里出错了?
有没有一种特殊的方法来创建我缺少的类?

注意:从结构的角度来看,我的 JSON 对象是完全有效的。如果您看到任何错误,可能是因为它们在我手动创建上述虚拟/演示时出现了错误。

最佳答案

只需关注GSON Collections good practices ,尝试改变

 Client[] clientsArray= (new Gson()).fromJson(jsonClients, Client[].class);

 Type collectionType = new TypeToken<List<Client>>(){}.getType();
List<Client> clientsArray = (new Gson()).fromJson(jsonClients, collectionType);

关于java - 使用 GSON 解析 JSON 内部字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31591856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com