Using GSON in Android to parse a complex JSON object

前端 未结 2 1545
旧巷少年郎
旧巷少年郎 2020-12-01 11: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

相关标签:
2条回答
  • 2020-12-01 11:39

    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.

    0 讨论(0)
  • 2020-12-01 12:06

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题