How parse json array with multiple objects by gson?

后端 未结 3 1277
陌清茗
陌清茗 2020-12-10 16:52

How can I parse json using gson? I have a json array with multiple object types, and I don\'t know, what kind of object I need to create to save this structure. I cannot cha

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 17:20

    This may be a bit late for the original poster, but hopefully it will help someone else.

    I am using Gson in Android. I have seen everyone use custom classes and long way round solutions. Mine is basic.

    I have an ArrayList of many different Object types (Models for my database) - Profile is one of them. I get the item using mContactList.get(i) which returns:

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

    Now I create the Gson object:

    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)); 
    

    Now instead of creating a custom class - just pass it through as a JsonObject using the following code:

    JsonObject obj = gson.fromJson(str_obj, JsonObject.class);
    

    And now, you can call the object like so:

    JsonObject profile = obj.getAsJsonObject("profile");
    

提交回复
热议问题