How do I parse a field from a deep nested json object using Gson and retrofit in android?

后端 未结 3 1058
南旧
南旧 2021-01-26 01:06

I have a unique situation where I have to get certain times from a json\'s deeply nested object. It\'s a little complex, I couldn\'t find a solution so looking for ideas and way

3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-26 01:29

    You can use google GSON for parsing this JSON. Here's the link for google GSON is [https://search.maven.org/artifact/com.google.code.gson/gson/2.8.5/jar].

    That would be a better alternative than creating classes. Just click on the Downloads section on the right side of the page (the page resulting from the above link) and download the Jar file and the sources file too if you would like to debug using the actual source. Finally, include these in your project.

    As far as the code is concerned, here is a snippet from what I have written:

    import com.google.gson.JsonArray;
    import com.google.gson.JsonElement;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import java.io.File;
    import java.io.FileReader;
    import java.util.logging.Logger;
    
    public class JSONTester {
    
        private static File json = new File("/Users/XXXX/Production/StackOverFlow/JSON_From_https-::stackoverflow.com:questions:56501897:how-do-i-retrieve-json-from-a-deep-nested-object#56501897.json");
        private static Logger jsonLogger = Logger.getLogger(JSONTester.class.getSimpleName());
    
    
        public static void main(String[] args) {
            JsonElement jsonElement;
            try {
                jsonElement = new JsonParser().parse(new FileReader(json));
            } catch (Exception e) {
                jsonLogger.severe("There was an error parsing the JSON with message " + e.getLocalizedMessage());
                return;
            }
    
            if (jsonElement != null) {
                if (jsonElement instanceof JsonArray) {
                    JsonArray jsonArray = (JsonArray) jsonElement;
                    for (int i = 1; i < jsonArray.size(); i++) {
                        JsonElement element = jsonArray.get(i);
                        //We are considering only JSON objects inside a JSONArray.
                        if (element instanceof JsonObject) {
                            JsonObject jsonObject = (JsonObject) element;
                            if (jsonObject.has("busyAt")) {
                                JsonArray busyAtJsonArray =
                                        jsonObject.getAsJsonArray("busyAt");
                                if (busyAtJsonArray != null && busyAtJsonArray.size() >
                                        0) {
                                    //You got the busyAt json array. Now, since you already know
                                    //that events is another JSONArray within busyAt array, process this
                                    //array accordingly. Get the first JsonObject from the events
                                    //array to get "started_at" and "ended_at" fields from
                                    //this (first) json object.
                                                                        //busyAt.get(0) = from,to,events[],
                                    JsonObject firstJsonObject = (JsonObject) busyAtJsonArray.get(0);
                                    JsonArray eventsArray = firstJsonObject.getAsJsonArray("events");
                                    JsonObject eventsFirstObject = (JsonObject) eventsArray.get(0);
                                    String started_At = eventsFirstObject.get("started_at").getAsString();
                                    String ended_At = eventsFirstObject.get("ended_at").getAsString(); 
    
                                }
                            }
                        }
                    }
                }
            }
        }
    } 
    

    Please note that I have been careful in assuming whether a JsonElement is a JsonArray or JsonObject. You should also try doing that so that when you encounter any exceptions, you will know what caused it. Obviously, you will get class cast exceptions (or others depending on what you were doing wrong), but it is a good idea to keep a track of why it happened.

    For more details, go through the GSON library documentation (link https://sites.google.com/site/gson/gson-user-guide) and how to parse Json objects, Json Arrays etc. This will clearly explain the benefits of using GSON and its advantages over other methods of JSON parsing. The basic element you get when you parse either one of these will be JsonElement. You can then cast it to either of the above depending on what you think is the right element there (json object or array). Or, if you are well-versed with the JSON structure, you can just cast it and get the results accordingly.

提交回复
热议问题