[英]How to Parse JSON object partially to Java object
I am working on a big json output file which is coming as response but I want to parse only some of the fields in my logic.我正在处理一个大的 json 输出文件,它作为响应出现,但我只想解析逻辑中的一些字段。
For ex: The JSON
looks like this例如:
JSON
看起来像这样
{
"lastName":"Smith",
"address":{
"streetAddress":"21 2nd Street",
"city":"New York",
"state":"NY",
"postalCode":10021
},
"age":25,
"phoneNumbers":[
{
"type":"home", "number":"212 555-1234"
},
{
"type":"fax", "number":"212 555-1234"
}
],
"firstName":"John"
}
I have created the necessary JAVA classes and mapping the JSON
Object to Java object using GSON
.我已经创建了必要的 JAVA 类并使用
GSON
将JSON
对象映射到 Java 对象。 Since, the above JSON
is just a sample one in my case I have big one which is generating around 15 classes.因为,上面的
JSON
只是我的例子中的一个示例,我有一个很大的一个,它生成了大约 15 个类。
Currently i have to create following classes files:目前我必须创建以下类文件:
- Employee.class
- Address.class
- PhoneNumber.class
I want to avoid creating PhoneNumber.class and its nested class using GSON.我想避免使用 GSON 创建 PhoneNumber.class 及其嵌套类。
Basically My query is like in above json I don't want phoneNumbers
and its internal objects
so how can i ignore those fields so that i have to construct less Java Class files and still it is mapped to Java Object
.基本上我的查询就像上面的 json 我不想要
phoneNumbers
和它的内部objects
所以我怎么能忽略这些字段,这样我就必须构造更少的 Java Class 文件,但它仍然映射到 Java Object
。
So I want to avoid making classes for PhoneNumbers
fields and the nested fields inside PhoneNumbers.所以我想避免为
PhoneNumbers
字段和PhoneNumbers
的嵌套字段创建类。
As suggested, Employee
and Address
classes are all you need:正如建议的那样,您只需要
Employee
和Address
类:
public class Employee {
private String firstName, lastName;
private int age;
private Address address;
}
public class Address {
private String streetAddress, city, state;
private int postalCode;
}
new Gson().fromJson(json, Employee.class);
, where json
is the raw JSON string, should then do what you want. ,其中
json
是原始 JSON 字符串,然后应该执行您想要的操作。 Without sharing your code, it is hard to tell why it doesn't work for you.如果不共享您的代码,很难说出为什么它不适合您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.