2

I have a 3 object value from JSON, and the second object is dynamic value, i.e. it can be an array or an object. So it look like this one :

{
 obj1 : {....},
 dynamicObj2 : {....}, // it can be object or array
 obj3 : {....}
}

So, my question is how can this be achieved in the POJO class? I am using GSON for this case. And it will be implemented at Android end and I am using retrofit for the networking library. Any suggestion for POJO class? Or I must use manual String object and parsing one by one?

KayV
  • 12,987
  • 11
  • 98
  • 148
  • 1
    You can use Object class : https://developer.android.com/reference/java/lang/Object.html – Ahmed Abidi Feb 13 '17 at 10:28
  • @AhmedAbidi so, you mean I must cast this object by the type of data that I get from JSON? – Muhammad Nafian Wildana Feb 13 '17 at 10:32
  • I don't really think that is needed, GSON will handle that – Ahmed Abidi Feb 13 '17 at 10:41
  • @MuhammadNafianWildana Yes, you have to cast explicitly or implicitly. Gson will construct either `Map` or `List>` due to lack of type information. You might be interested in a similar solution that uses custom deserializing techniques and tries to generalize to more contcrete objects based on the initially known response element type: http://stackoverflow.com/questions/41466633/gson-how-to-handle-a-field-that-may-have-a-different-type/41480514#41480514 – Lyubomyr Shaydariv Feb 13 '17 at 12:09

1 Answers1

1

If the Object it can be is of the same kind as the elements in the Array just make it always an array in your Java Class. if not then you will need to use the Object class and cast it to the appropriate type you want later.

You can also automatically generate a POJO using this tool: http://www.jsonschema2pojo.org/ You can even make it serializable, parcelable, and so on. Just check Gson and preview to see if the class is in your liking.

Raeglan
  • 514
  • 1
  • 5
  • 17