在尝试理解和学习JSON时,我遇到了一个问题:
{
"items": [
{
"id": "353453",
"count": 2,
"amount": 50
},
{
"id": "3534534",
"count": 1,
"amount": 1.9
},
{
"id": "23423423",
"count": 2,
"amount": 1.1
},
{
"id": "2342234",
"count": 3,
"amount": 32.9
}
],
"oid": 1000000009
}
到目前为止我编码的是什么:
public class Test {
public static void main(String... args) throws Exception {
String json = "{\"items\":[{\"id\":\"353453\",\"count\":2,\"amount\":50.00},{\"id\":\"3534534\",\"count\":1,\"amount\":1.90},{\"id\":\"23423423\",\"count\":2,\"amount\":1.10},{\"ean\":\"2342234\",\"count\":3,\"amount\":32.90}],\"oid\":1000000009}";
System.out.println(dojObject.getItems().get(0).getID());
}
}
class DataOrderJson {
private List<ItemDetails> items;
private Long oid;
public DataOrderJson() {
}
public Long getOid() {
return oid;
}
public List<ItemDetails> getItems() {
return items;
}
public void setOid(Long oid) {
this.oid = oid;
}
public void setItems(List<ItemDetails> items) {
this.items = items;
}
@Override
public String toString() {
return String.format("{items:%s,oid:%s}", items, oid);
}
}
class ItemDetails {
private String id;
private Long count;
private Float amount;
public ItemDetails() {
}
public String getID() {
return id;
}
public Long getCount() {
return count;
}
public Float getAmount() {
return amount;
}
public void setID(String id) {
this.ean = ean;
}
public void setCount(Long count) {
this.count = count;
}
public void setAmount(Float amount) {
this.amount = amount;
}
@Override
public String toString() {
return String.format("{id:%s,count:%s,amount:%s}", id, count, amount);
}
}
按预期输出: 353453
现在我想检查id是否是json字符串的一部分。我有麻烦将json对象的lsit转换为java对象列表。 如何将json对象放入列表并遍历此列表?
答案 0 :(得分:0)
你需要创建twi java对象:
class Order {
private List<Item> items;
private Long orderid;
Order(){}
}
和
Class Item {
private String ean;
private Long count;
private Float amount;
Item(){}
}
然后打电话:
Order jobj = new Gson().fromJson(json, Order.class);
为了能够解析json,你需要表示与json对象相同的属性名的对象。