简体   繁体   中英

How to parse this kind of json String using Gson?

{
    "status": "Success",
    "message": "Contents retrieved successfully",
    "name": {
        "1": "God",
        "2": "Goat"
    },
    "sites": {
        "1": "google",
        "2": "yahoo",
        "3": "bing"
    },
    "places": [
        "UK",
        "AU",
        "US"
    ],
    "images": {
        "1": {
            "1x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png",
            "2x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png"
        },
        "2": {
            "1x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png",
            "2x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png"
        },
        "3": {
            "1x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png",
            "2x": "http://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png"
        }
    }
}

My Class

import java.util.Map;

public class Data {

    String status;
    String message;
    Map<String, String> name;
    Map<String, String> Sites;
    @Override
    public String toString() {
        return "Data [status=" + status + ", message=" + message
                + ", name=" + name + ", Sites=" + Sites
                + "]";
    }


}

this class returns null value for the while retrieving sites and names

name and sites are JSONObjects no Arrays. Any Object in a JSON have to deserialised in a class using GSON.

So try this,

public class MyJson {
    String status;
    String message;

    Sites sites;
    List<String> places;
}

public class Sites {
    String 1;
    String 2;
    String 3;
}

and so on for every Object. For Arrays you can use List / Map.

To use it make a call like this:

Gson gson = new Gson();
MyJson myJson = gson.fromJson(yourJsonString, MyJson.class);
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject)parser.parse(yourString);

for (Map.Entry<String,JsonElement> entry : object.entrySet()) {
    JsonArray array = entry.getValue().getAsJsonArray();
    for (JsonElement elementJSON : array) {
        [...]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM