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

后端 未结 3 1066
南旧
南旧 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条回答
  •  离开以前
    2021-01-26 01:37

    I use this : http://www.jsonschema2pojo.org/ to generate a class from the above json string. I was wondering how do I retrieve the "started_at": "2019-06-07T19:00:00-0400", from busyAt-> events into my main model class generated by the above site? Say at the same level as mySpaceId. I currently use the following :

    If I interpret you correctly, you have created using the www.jsonschema2pojo.org the following classes: -

    • a class called "Entity" that contains "mySpaceId" and a list of "BusyAt".
    • class "BusyAt" contains a list of "Event".
    • class "Event" contain a String called StartedAt.

    I assume that you want to retrieve the First entry of each list (if it exist) directly from the top-most class ("Entity")

    something like: -

    entity.busyAt(0).events(0).startedAt
    if either busyAt or event list is empty or null, then return empty string for startedAt.

    what you can do, is to create the following method in the "Entity" class (root class containing both mySpaceId, and List).

    public String getStartedAt(){
      //check if the busyAt List contains items or not.
      if (busyAt ==null || busyAt.isEmpty()){
        return "";
      }
      //take the list of events from the first busyAt in the array
      List eventList = busyAt.get(0).getEvents();
      //check if the event List contains items or not.
      if (eventList ==null || eventList.isEmpty()){
        return "";
      }
      //return the StartAt value of the first event.
      return eventList.get(0).getStartedAt(); 
    }
    

提交回复
热议问题