如何解析JSON与GSON响应(不同的对象类型) [英] How to parse JSON response (different object types) with GSON

查看:192
本文介绍了如何解析JSON与GSON响应(不同的对象类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:解析来自Foursquare的场地API以下响应:

Problem: parse the following response from Foursquare Venues API:

{
    meta: {
        code: 200
    }
    notifications: [
    {
        type: "notificationTray"
        item: {
        unreadCount: 0
        }
    }
    ]
    response: {
        venues: [
        {
            id: "5374fa22498e33ddadb073b3"
            name: "venue 1"
        },
        {
            id: "5374fa22498e33ddadb073b4"
            name: "venue 2"
        }
        ],
        neighborhoods: [ ],
        confident: true
    }
}

的<一个href="https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types"相对=nofollow> GSON文档网站建议使用GSON的解析API来解析响应为JSONArray,然后读取每个数组项到一个合适的对象或数据类型(例如<一个href="https://$c$c.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java"相对=nofollow>这里)。因此,我本来切换到下面的实现:

The GSON documentation website recommends using GSON's parse API to parse the response as a JSONArray and then read each array item into an appropriate Object or data type (Example here). As such, I originally switched to the following implementation:

JsonParser parser = new JsonParser();
                try {
                    JSONObject json = new JSONObject(response);
                    JSONArray venues = json.getJSONObject("response").getJSONArray("venues");

                    int arraylengh = venues.length();
                    for(int i=0; i < arraylengh; i++){
                        Log.d(TAG, "The current element is: " + venues.get(i).toString());
                    }
                }
                catch(JSONException e){

                }

在code以上给了我一个JSONArray与所有的场地。接下来的问题是,我不知道如何解析/转换场地JSONArray成的ArrayList(我的自定义地点对象)。

The code above gave me a JSONArray with all the "venues". The next problem was that I do not know how to parse/convert the "venues" JSONArray into a ArrayList (for my custom Venue object).

解决方法:作为概述了JohnUopini答案,我是能够成功地解析JSON通过以下实现:

Solution: As outlined on JohnUopini answer I was able to successfully parse the JSON by using the following implementation:

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();

JsonParser parser = new JsonParser();
JsonObject data = parser.parse(response).getAsJsonObject();
Meta meta = gson.fromJson(data.get("meta"), Meta.class);
Response myResponse = gson.fromJson(data.get("response"), Response.class);
List<Venue> venues = Arrays.asList(myResponse.getVenues());

通过上面的code,我能够成功地解析了元,以及在回应JSON性质为我的自定义对象。

With the above code I was able to successfully parse the "meta" as well as the "response" JSON properties into my custom objects.

有关参考,下面是我的回应类(注:该属性被定义为公共用于测试目的的最终实现应该有这些声明为private和使用的setter / getter方法​​进行封装。):

For reference, below is my Response class (NOTE: The properties were defined as public for testing purposes. A final implementation should have these declared as private and use setters/getters for encapsulation):

public class Response {

    @SerializedName("venues")
    public Venue[] venues;

    @SerializedName("confident")
    public boolean confident;

    Response(){}
}

注意/意见:实施接受答案的建议后,一对夫妇的时候,我在我的调试过程中遇到了以下(或类似)异常消息:

Note/Feedback: After implementing the accepted answer's recommendation, a couple of times I encountered the following (or similar) exception message during my debugging process:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT

我之所以得到了上面的异常是由于一些内部的场地的孩子们的类型的JSON没有与型符合我在我的自定义地点类中定义这样的对象。请确保输入您的自定义类有一个1对1的对应的JSON(即[]是一个数组属性,{}是一个对象的属性,等等)。

The reason I was getting the above exception was because the "type" on some of the children inside the "venues" JSON did not match with the "type" I defined such objects in my custom Venue class. Make sure the type in your custom Classes has a 1-to-1 correspondence with the JSON (i.e. [ ] is a array property, { } is an Object property, etc).

推荐答案

这是正确的,因为你要访问的对象不是一个数组,你应该做的是这样的:

This is correct because the object you are trying to access is not an array, you should do something like this:

JsonParser parser = new JsonParser();
JsonObject data = parser.parse(response).getAsJsonObject();
Meta meta = gson.fromJson(data.get("meta"), Meta.class);
Response myResponse = gson.fromJson(data.get("response"), Response.class);

或者你也可以创建一个包含3类,针对3个对象的对象,然后通过GSON解析一切。

Or you can create an object containing 3 classes for the 3 objects and then parse everything through GSON.

这篇关于如何解析JSON与GSON响应(不同的对象类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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