合并Json对象

时间:2015-07-22 07:31:34

标签: java json gson

我有两个jsons

2. 



       {"root": {
            "item": {
                "groupName": "Al Karama Fire Station",
                "vehicleId": 222,
                "speed": 1
            },
            "rowCount": 1
        }}
{"root": {
    "item": [
        {
            "groupName": "Al Karama Fire Station",
            "vehicleId": 211,
            "speed": 81
        },
        {
            "groupName": "Al Karama Fire Station",
            "vehicleId": 137,
            "speed": 83
        },
        {
            "groupName": "Al Karama Fire Station",
            "vehicleId": 222,
            "speed": 1
       }
    ],
    "rowCount": 3
}}

理想情况下,第二个json应该给我一个“项目”列表,但它没有发生。我需要转换合并两个json以得到一个组合。

预期:

public class ParentDTO {

    private RootDTO root;

    public RootDTO getRoot() {
        return root;
    }
    public void setRoot(RootDTO root) {
        this.root = root;
    }
}

public class RootDTO {
     private List<ItemDTO> item = new ArrayList<ItemDTO>();
     private Integer rowCount;

    public List<ItemDTO> getItem() {
        return item;
    }
    public void setItem(List<ItemDTO> item) {
        this.item = item;
    }
    public Integer getRowCount() {
        return rowCount;
    }
    public void setRowCount(Integer rowCount) {
        this.rowCount = rowCount;
    }
}

public class ItemDTO {

    private String groupName;
    private String vehicleId;
    private Long speed;

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public String getVehicleId() {
        return vehicleId;
    }

    public void setVehicleId(String vehicleId) {
        this.vehicleId = vehicleId;
    }

    public Long getSpeed() {
        return speed;
    }

    public void setSpeed(Long speed) {
        this.speed = speed;
    }
}

为实现这一目标,我创建了以下DTO。

Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 2 column 14 path $.root.item

我的问题是,在合并时,我正在

{"root": {
        "item": [
         {
            "groupName": "Al Karama Fire Station",
            "vehicleId": 222,
            "speed": 1
        }
        ],
        "rowCount": 1
    }}

如果我能得到第二个json如下,代码工作正常。

Gson gson = new Gson();
ParentDTO  updatedloginDto2 = gson.fromJson(tmp1, ParentDTO .class);

请建议。

解析Json的代码

{{1}}

1 个答案:

答案 0 :(得分:2)

您必须创建两个根DTO - 一个用于具有子级列表的根,一个用于具有单个子级的根,并且在解组JSON之后将“单个子”元素添加到具有子级列表的根。

编辑:

public class RootSingleChildDTO {
     private ItemDTO item;
     private Integer rowCount;

    public ItemDTO getItem() {
        return item;
    }
    public void setItem(ItemDTO item) {
        this.item = item;
    }
    public Integer getRowCount() {
        return rowCount;
    }
    public void setRowCount(Integer rowCount) {
        this.rowCount = rowCount;
    }
}