0

在尝试理解和学习 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 对象放入列表并遍历该列表?

4

1 回答 1

0

你需要创建两个 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 对象具有相同属性名称的对象。

于 2013-03-08T15:20:13.113 回答