我有一个下面的JSON文档,其中items
是一个包含多个item
对象的数组。每个item
对象都有许多字段,如下所示。为简单起见,我在item
数组中只显示一个items
对象,但它可以有更多。
{
"items": [{
"createDate": 1234567890,
"title": "some title",
"bp": {
"currencyId": "USD",
"value": 10.0
},
"pof": false,
"ku": true,
"var": {
"quant": 10,
"tot": 0,
"co": 1,
"vbp": {
"cid": "USD",
"val": 10.0
},
"id": 5296164,
"sel": {
"style": "Short",
"Size": "L",
"Color": "Blue"
}
},
"flags": {
"low": false,
"rpl": false,
"scmb": false
}
"shipping": {
"shippingType": "sss"
},
"seller": {
"name": "",
"sco": 0,
"perc": 0.0,
"id": 101215,
"brand": true,
"prog": "NONE"
},
"dur": "DA9",
"urls": ["world", "hello"],
"itemId": 1234
}
],
"count": {
"ac": 3,
"ed": 0
}
}
如何使用Gson将我的上述JSON解析为POJO?我很困惑,因为它中有很多JSON对象字段,所以无法理解如何创建一个可以容纳所有这些东西的类。
答案 0 :(得分:1)
示例用法:
jsonschema2pojo --source ../Items.json --target java-gen -a GSON -T JSON -E
输出:
Bp.java Count.java Flags.java Item.java Sel.java Seller.java Shipping.java Items.java Var.java Vbp.java
Seller.java
public class Seller {
@SerializedName("name")
@Expose
private String name;
@SerializedName("sco")
@Expose
private Integer sco;
@SerializedName("perc")
@Expose
private Double perc;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("brand")
@Expose
private Boolean brand;
@SerializedName("prog")
@Expose
private String prog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSco() {
return sco;
}
public void setSco(Integer sco) {
this.sco = sco;
}
public Double getPerc() {
return perc;
}
public void setPerc(Double perc) {
this.perc = perc;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Boolean getBrand() {
return brand;
}
public void setBrand(Boolean brand) {
this.brand = brand;
}
public String getProg() {
return prog;
}
public void setProg(String prog) {
this.prog = prog;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
将所有这些类放入包中。
items
然后你可以反序列化
String line = "{}" // Read JSON in.
Gson gson = new GsonBuilder().create();
Items items = gson.fromJson(line, Items.class);