Vishal G. Gohel
Vishal G. Gohel

Reputation: 1033

Retrofit 2.0: how to generate pojo class for dynamic objects

enter image description here How could I generate pojo class for above type of response.

I already tried http://www.jsonschema2pojo.org/ and RoboPOJOGenerator

My JSON String is blow if you want to try.

{
"availableDates": {
    "2017-12-31": {
        "from": "08:00",
        "to": "17:00"
    },
    "2017-12-21": {
        "except": [
            {
                "from": "14:00:00",
                "to": "14:10:00"
            },
            {
                "from": "14:11:00",
                "to": "14:21:00"
            }
        ]
    }
}

}

Upvotes: 1

Views: 5577

Answers (3)

Pankaj Kumar
Pankaj Kumar

Reputation: 83008

You can not do that dynamically. Although you can parse such JSON using HashMap.

If you are interested to do that, use below syntax for page section

private HasMap<String, Page> pages;

It will parse JSON of pages into above HashMap. You will have "1", "2" etc as Key and Page as value for that.


As per you current JSON, solution would be

public class AvalDate {
  private HashMap<String, AvailableTimeSlot> availableDates;
}

public class AvailableTimeSlot {
  private String from;
  private String to;
  private ArrayList<ExceptTimeSlots> except;
}

public class ExceptTimeSlots {
  private String from;
  private String to;
}

Now you can read parsed values as

HashMap<String, AvailableTimeSlot> slots = avalDate.geAavailableDates();
Set keys = slots.keySet();
for (String date : keys) {
  // Here date is 2017-12-31
  AvailableTimeSlot avt = slots.get(date);

  // You can check if except available or not
  if (avt.getExcept() != null) {
    // Read array list of except for that day
    ArrayList<ExceptTimeSlots> except = avt.getExceps();
    // Do whatever you want to do with array
  } else {
    // you can read from and to directlly
    avt.getFrom();
    avt.getTo();
  }
}

Upvotes: 3

user9126652
user9126652

Reputation:

Fellow eager-to-downvote-rookies-SO-users, I understand this is just a clarification, but I can't comment it, so here I go with the blessing of your down-votes.

OP, select these options in this site: 1) Target language as Java,
2) Source type as JSON,
3) Annotation style as Gson

and then try to generate the POJO classes.

Upvotes: 0

Muhammad Saad Rafique
Muhammad Saad Rafique

Reputation: 3189

1) Go to http://www.jsonschema2pojo.org/

2) Paste your response over there and enter package and class name

3) Choose target language as Java

4) Source type as Json

5) Annotation style as Gson

6) Click Preview

7) Copy and paste those classes to your app package

Upvotes: 5

Related Questions