Using GSON in Android to parse a complex JSON obje

2019-01-08 23:13发布

I'm relatively new to Java programming and need to parse a complex JSON object across the wire. I've been reading documentation on GSON the past day and Haven't had much luck being able to fully parse this type of structure:

{
  'Events' : [{
    'name' : 'exp',
    'date' : '10-10-2010',
    'tags' : ["tag 1", "tag2", "tag3"]
    },...more events...],
  'Contacts' : [{
    'name' : 'John Smith',
    'date' : '10-10-2010',
    'tags' : ["tag 1", "tag2", "tag3"]
    },...more contacts...],
}

I've been able to get it to work similarly to this question but can't figure out how to get that additional array level to work.

2条回答
迷人小祖宗
2楼-- · 2019-01-08 23:56

The correct way to do it using GSON in the format I'm looking for is:

//somewhere after the web response:
Gson gson = new Gson();

Event[] events = gson.fromJson(webServiceResponse,  Event[].class);


//somewhere nested in the class:
static class Event{
    String name;
    String date;

    public String getName()
    {
        return name;
    }

    public String getDate()
    {
        return date;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setDate(String date)
    {
        this.date = date;
    }
}
查看更多
Ridiculous、
3楼-- · 2019-01-09 00:16

Java has his own JSON parser: we can use it on Android as well.

Below you can find how you can get all events from your String.

String TAG        = "JSON EXAMPLE";
    String jsonString = "{\"Events\" : [{\"name\" : \"exp\",\"date\" : \"10-10-2010\",\"tags\" : [\"tag 1\",\"tag 2\",\"tag 3\"]}],\"Contacts\" : [{\"name\" : \"John Smith\",\"date\" : \"10-10-2010\",\"tags\" : [\"tag 1\",\"tag 2\",\"tag 3\"]}]}";

    try {
        JSONObject jsonObj    = new JSONObject(jsonString);     // create a json object from a string
        JSONArray  jsonEvents = jsonObj.getJSONArray("Events"); // get all events as json objects from Events array

        for(int i = 0; i < jsonEvents.length(); i++){
            JSONObject event = jsonEvents.getJSONObject(i); // create a single event jsonObject
            Log.e(TAG, "Event name:" + event.getString("name") + " date: " + event.getString("date"));


            JSONArray eventTags = event.getJSONArray("tags");

            for(int j = 0; j < eventTags.length(); j++){
                Log.e(TAG, "Event tag: " + eventTags.getString(j));
            }

        }           

    } catch (JSONException e) {
        e.printStackTrace();
    }

Be aware: Your JSON Object(from your question) will throw a exception because it is not valid( I'm not sure, but it look like a javascript object). You have to add some quotes to each property(key) and ecape them with \ (\").
This tool is really nice to test if a JSON String is valid or not.

查看更多
登录 后发表回答