简体   繁体   English

如何使用Gson解析这种json String?

[英]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; 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 此类为检索站点和名称时返回null值

name and sites are JSONObjects no Arrays. 名称和站点是JSONObjects no Arrays。 Any Object in a JSON have to deserialised in a class using GSON. JSON中的任何对象都必须使用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) {
        [...]
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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