有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何解析JSON,如果某个元素有时作为jsonobject,有时作为jsonarray

我有来自服务的json响应提交。 对于一个元素,有时它是json数组,有时它是json对象

例如:

Response 1:
{"_id":2,"value":{id: 12, name: John}}
Response 2:
{"_id":1,"value":[{id: 12, name: John}, {id: 22, name: OMG}]}

这里的值是响应1中的jsonObject和响应2中的jsonArray

问题是我正在使用Gson解析json。并在我的POJO类中将值保留为ArrayList

public class ResponseDataset {
    private int _id;
    private ArrayList<Value> value;

    // getter setter
}

public class Value {
    private int id;
    private String name;

    // getter setter
}

我有没有办法用Gson处理这个问题。我的json响应太大和复杂,因此希望避免逐行解析


共 (2) 个答案

  1. # 1 楼答案

    在这里找到了解决方案 Gson handle object or array

    @Pasupathi您的解决方案也是正确的,但我想要一种使用Gson的方法,因为我的服务响应太大、太复杂

  2. # 2 楼答案

    即使我有同样的问题,我也做了如下的事情

        String jsonString = "{\"_id\":1,\"value\":[{id: 12, name: John}, {id: 22, name: OMG}]}";
        JSONObject jsonObject = new org.json.JSONObject(jsonString);
        ResponseDataset dataset = new ResponseDataset();
        dataset.set_id(Integer.parseInt(jsonObject.getString("_id")));
        System.out.println(jsonObject.get("value").getClass());
        Object valuesObject = jsonObject.get("value");
        if (valuesObject instanceof JSONArray) {
            JSONArray itemsArray =(JSONArray) valuesObject;
            for (int index = 0; index < itemsArray.length(); index++) {
                Value value = new Value();
                JSONObject valueObject = (JSONObject) itemsArray.get(index);
                value.setId(Integer.parseInt(valueObject.getString("id")));
                value.setName(valueObject.getString("name"));
                dataset.getValue().add(value);
            }
        }else if(valuesObject instanceof JSONObject){
            Value value = new Value();
            value.setId(Integer.parseInt(((JSONObject)valuesObject).getString("id")));
            value.setName(((JSONObject)valuesObject).getString("name"));
            dataset.getValue().add(value);
        }
    

    你可以试试这个