簡體   English   中英

如何通過gson解析json數組與多個對象?

[英]How parse json array with multiple objects by gson?

如何使用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"
    }
  }
]

這種json結構固有地對gson不友好。 即你不能在java中干凈地建模,因為“對象”鍵指的是動態類型。 你可以用這個結構做的最好的模型是這樣的:

    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"
    }
  }
]

對於原始海報來說,這可能有點晚了,但希望它會幫助其他人。

我在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");

您可以非常輕松地在模型類中設置方法。 只需創建一個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);

我用來從你的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;
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM