使用gson解析嵌套的JSON [英] Parse a nested JSON using gson

查看:93
本文介绍了使用gson解析嵌套的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  {
回复:{
MetaInfo:{
时间戳:2011-11-21T14:55:06.556Z

View:[
{
_type:SearchResultsViewType,
ViewId:0,
结果 :[
{
相关性:0.56,
MatchQuality:{
国家:1,
州:1,
County:1,
City:1,
PostalCode:1
},
Location:{
LocationType:point ,
DisplayPosition:{
Latitude:50.1105,
经度:8.684
},
MapView:{
_type:GeoBoundingBoxType,
TopLeft:{
Latitude:50.1194932,
Longitude:8.6699768
} ,
BottomRight:{
Latitude:50.1015068,
经度:8.6980232
}
},
地址:{
Country:DEU,
State:Hessen,
County:Frankfurt am Main,
City ,
区域:法兰克福,
PostalCode:60311 ,
AdditionalData:[
{
value:Germany,
key:CountryName
}
]
}
}
}
]
}
]
}
}

我试图从上面的JSON中检索邮政编码。我正在使用gson来解析它。我对JSON非常陌生,从我从这里发布的所有帖子(有些与此非常相似)中读到的内容中,我了解到字段名称应该保持原样。所以我明白我必须做出4个课,即回应,观看,结果和地址。我让它们成为静态嵌套类,但是我只获得空值作为输出。在下一个JSON中,我有多个地址。但是我被困在这个单一的响应中。



对于一个简短的例子,我尝试用这段代码检索Timestamp,但它给了我一个空值

  public class ParseJSON {
public static void main(String [] args)throws Exception {
BufferedReader br = new BufferedReader新的FileReader(try.json));

Gson gson = new GsonBuilder()。create();
Pojo pojo = gson.fromJson(br,Pojo.class);
System.out.println(Pojo.Response.MetaInfo.Timestamp);
br.close();



class Pojo {
public Pojo(){}

static class Response {
static class MetaInfo {
static public String Timestamp;

public String getTimestamp(){
return Timestamp;
}
}
}
}


如果你只需要PostalCode,你可以使用 JsonParser 来代替有一堆类:

  JsonParser jsonParser = new JsonParser(); 
JsonObject address = jsonParser.parse(json)
.getAsJsonObject()。get(Response)
.getAsJsonObject()。getAsJsonArray(View)。get(0)
.getAsJsonObject()。getAsJsonArray(Result)。get(0)
.getAsJsonObject()。get(Location)
.getAsJsonObject()。getAsJsonObject(Address);
String postalCode = address.get(PostalCode)。getAsString();

或所有结果:

<$ p $ JSONArray results = jsonParser.parse(json)
.getAsJsonObject()。get(Response)
.getAsJsonObject()。getAsJsonArray(View)。get() 0)
.getAsJsonObject()。getAsJsonArray(Result); (JsonElement结果:结果){
JsonObject address = result.getAsJsonObject()。get(Location)。getAsJsonObject()。getAsJsonObject(Address);
String postalCode = address.get(PostalCode)。getAsString();
System.out.println(postalCode);
}


{
    "Response": {
        "MetaInfo": {
            "Timestamp": "2011-11-21T14:55:06.556Z"
        },
        "View": [
            {
                "_type": "SearchResultsViewType",
                "ViewId": 0,
                "Result": [
                    {
                        "Relevance": 0.56,
                        "MatchQuality": {
                            "Country": 1,
                            "State": 1,
                            "County": 1,
                            "City": 1,
                            "PostalCode": 1
                        },
                        "Location": {
                            "LocationType": "point",
                            "DisplayPosition": {
                                "Latitude": 50.1105,
                                "Longitude": 8.684
                            },
                            "MapView": {
                                "_type": "GeoBoundingBoxType",
                                "TopLeft": {
                                    "Latitude": 50.1194932,
                                    "Longitude": 8.6699768
                                },
                                "BottomRight": {
                                    "Latitude": 50.1015068,
                                    "Longitude": 8.6980232
                                }
                            },
                            "Address": {
                                "Country": "DEU",
                                "State": "Hessen",
                                "County": "Frankfurt am Main",
                                "City": "Frankfurt am Main",
                                "District": "Frankfurt am Main",
                                "PostalCode": "60311",
                                "AdditionalData": [
                                    {
                                        "value": "Germany",
                                        "key": "CountryName"
                                    }
                                ]
                            }
                        }
                    }
                ]
            }
        ]
    }
}

I am trying to retrieve the postal code from the above JSON. I am using gson to parse it. I am very new to JSON and from what i read from all the posts here(some very similar to this), I understood that the fields name should be as it is. So I understand i have to make 4 classes viz Response, view, Result and Address. I made them static nested classes, but I am only getting null value as output. In the next JSON, I have multiple addresses. But I am stuck on this single response.

For a short example, I try to retrieve Timestamp with this code, but it gives me a null value

public class ParseJSON {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("try.json"));

        Gson gson = new GsonBuilder().create();
        Pojo pojo = gson.fromJson(br,Pojo.class);
        System.out.println(Pojo.Response.MetaInfo.Timestamp);
        br.close();
    }
}

class Pojo {
    public Pojo() { }

    static class Response{
        static class MetaInfo {
            static public String Timestamp;

            public String getTimestamp() {
                    return Timestamp;
            }
        }
    }
}

解决方案

If you only need the "PostalCode", you could use JsonParser instead of having a bunch of classes:

JsonParser jsonParser = new JsonParser();
JsonObject address = jsonParser.parse(json)
    .getAsJsonObject().get("Response")
    .getAsJsonObject().getAsJsonArray("View").get(0)
    .getAsJsonObject().getAsJsonArray("Result").get(0)
    .getAsJsonObject().get("Location")
    .getAsJsonObject().getAsJsonObject("Address");
String postalCode = address.get("PostalCode").getAsString();

or for all results:

JsonArray results = jsonParser.parse(json)
        .getAsJsonObject().get("Response")
        .getAsJsonObject().getAsJsonArray("View").get(0)
        .getAsJsonObject().getAsJsonArray("Result");
for (JsonElement result : results) {
    JsonObject address = result.getAsJsonObject().get("Location").getAsJsonObject().getAsJsonObject("Address");
    String postalCode = address.get("PostalCode").getAsString();
    System.out.println(postalCode);
}

这篇关于使用gson解析嵌套的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆