如何使用Gson解析包含多个对象的JSON数组?

8

我该如何使用gson解析json数据?我的json数组有多种对象类型,我不知道需要创建哪种类型的对象来保存这种结构。我不能更改json数据格式(我无法控制服务器)。

我能否使用gson或其他库来解析此json数组,应该如何操作?

以下是json代码块:

[
  {
    "type": 1,
    "object": {
      "title1": "title1",
      "title2": "title2"
    }
  },
  {
    "type": 2,
    "object": [
      "string",
      "string",
      "string"
    ]
  },
  {
    "type": 3,
    "object": [
      {
        "url": "url",
        "text": "text",
        "width": 600,
        "height": 600
      },
      {
        "url": "url",
        "text": "text",
        "width": 600,
        "height": 600
      }
    ]
  },
  {
    "type": 4,
    "object": {
      "id": 337203,
      "type": 1,
      "city": "1"
    }
  }
]

嗨!你读过并尝试了我的答案吗? - BNK
3个回答

8

这个json结构本质上不适合用gson处理。也就是说,您无法在Java中干净地建模,因为"object"键引用了动态类型。您可以使用以下方式对此结构进行建模:

    public class Models extends ArrayList<Models.Container> {

    public class Container {
        public int type;
        public Object object;
    }

    public class Type1Object {
        public String title1;
        public String title2;
    }

    public class Type3Object {
        public String url;
        public String text;
        public int width;
        public int height;
    }

    public class Type4Object {
        public int id;
        public int type;
        public int city;
    }

}

然后需要在类型和对象字段上进行一些笨拙的切换:
String json = "{ ... json string ... }";
Gson gson = new Gson();
Models model = gson.fromJson(json, Models.class);


for (Models.Container container : model) {

    String innerJson = gson.toJson(container.object);

    switch(container.type){
        case 1:
            Models.Type1Object type1Object = gson.fromJson(innerJson, Models.Type1Object.class);
            // do something with type 1 object...                                
            break;
        case 2:
            String[] type2Object = gson.fromJson(innerJson, String[].class);
            // do something with type 2 object...
            break;
        case 3:
            Models.Type3Object[] type3Object = gson.fromJson(innerJson, Models.Type3Object[].class);
            // do something with type 3 object...
            break;
        case 4:
            Models.Type4Object type4Object = gson.fromJson(innerJson, Models.Type4Object.class);
            // do something with type 4 object...
            break;

    }
}

最终的最佳解决方案是将json结构更改为与Java更兼容的格式。

例如:

[
  {
    "type": 1,
    "type1Object": {
      "title1": "title1",
      "title2": "title2"
    }
  },
  {
    "type": 2,
    "type2Object": [
      "string",
      "string",
      "string"
    ]
  },
  {
    "type": 3,
    "type3Object": [
      {
        "url": "url",
        "text": "text",
        "width": 600,
        "height": 600
      },
      {
        "url": "url",
        "text": "text",
        "width": 600,
        "height": 600
      }
    ]
  },
  {
    "type": 4,
    "type4Object": {
      "id": 337203,
      "type": 1,
      "city": "1"
    }
  }
]

4
这可能对原帖发布者来说有点晚了,但希望它能帮助其他人。
我在Android中使用Gson。我看到每个人都使用自定义类和冗长的解决方案。我的方法很基本。
我有一个许多不同对象类型(我的数据库模型)的ArrayList - 其中之一是Profile。我使用mContactList.get(i)获取项目,它返回:
{"profile": 
    {"name":"Josh",
     "position":"Programmer",
     "profile_id":1,
     "profile_image_id":10,
     "user_id":1472934469
    },
 "user":
    {"email":"example@you.co.za",
     "phone_numbers":[],
     "user_id":1,
     "user_type_id":1
    },
 "follower":
    {"follower_id":3,
     "following_date":1.4729345E9,
     "referred_by_id":2,
     "user_from_id":1,
     "user_to_id":2
    },
 "media":
    {"link":"uploads/profiles/profile-photos/originals/1-G9FSkRCzikP4QFY.png",
     "media_description":"",
     "media_id":10,
     "media_name":"",
     "media_slug":"",
     "medium_link":"uploads/profiles/profile-photos/thumbs-medium/1-G9FSkRCzikP4QFY.png",
     "thumbnail_link":"uploads/profiles/profile-photos/thumbs-small/1-G9FSkRCzikP4QFY.png",
     "uploader_id":1
    }
}

现在我创建一个Gson对象:
Gson gson = new Gson();
// this creates the JSON string you see above with all of the objects
String str_obj = new Gson().toJson(mContactList.get(i)); 

现在,不需要创建自定义类,只需使用以下代码将其作为JsonObject传递即可:
JsonObject obj = gson.fromJson(str_obj, JsonObject.class);

现在,您可以这样调用对象:
JsonObject profile = obj.getAsJsonObject("profile");

我怎样才能获取profile的name属性?@Haring10 - K.tas

0

您可以非常容易地在您的模型类中设置方法。只需创建一个StringRequest即可。以下是代码片段:

List<YourModelClass> inpList;
StringRequest greq = new StringRequest(Request.Method.POST, yourURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                        Log.d("response array===>  ", response.toString());

                        Type type = new TypeToken<List<YourModelClass>>(){}.getType();
                        inpList = new Gson().fromJson(response, type);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                //return params back to server, if any
            }
        };

        yourVolley.getRequestQueue().add(greq);

我使用 this 从你的 JSON 数据生成了模型类。你的模型类大致如下:

 package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class YourModelClass {

@Expose
private Integer type;
@Expose
private Object object;

/**
* 
* @return
* The type
*/
public Integer getType() {
return type;
}

/**
* 
* @param type
* The type
*/
public void setType(Integer type) {
this.type = type;
}

/**
* 
* @return
* The object
*/
public Object getObject() {
return object;
}

/**
* 
* @param object
* The object
*/
public void setObject(Object object) {
this.object = object;
}

}
-----------------------------------com.example.Object.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class Object {

@Expose
private Integer id;
@Expose
private Integer type;
@Expose
private String city;

/**
* 
* @return
* The id
*/
public Integer getId() {
return id;
}

/**
* 
* @param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}

/**
* 
* @return
* The type
*/
public Integer getType() {
return type;
}

/**
* 
* @param type
* The type
*/
public void setType(Integer type) {
this.type = type;
}

/**
* 
* @return
* The city
*/
public String getCity() {
return city;
}

/**
* 
* @param city
* The city
*/
public void setCity(String city) {
this.city = city;
}

}

但是该对象有四种类型,如何处理它? - rainash
您可以更改模型类并将对象定义为“对象”类的列表。例如,您将创建另一个类对象并单独定义其getter和setter。但是,我认为作为数组的对象值应该有一个与作为对象的对象值不同的名称。 - Kaveesh Kanwal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接