The api returns both an object and an array

Viewed 32

I'm new to json, there was a problem and I couldn't find a solution

I was given an api and when executing a get request, I get some object, but if there is no data in the object, an array is returned.

At the moment I was able to get Any?, instead of JSONArray or JSONObject, but there was a problem with converting Any? to the class

How to convert data to kotlin data class correctly?

returned object

returned array

The class I'm converting the json request to:

data class ProductInfo (var product:Product?,var specifications: JsonObject?,var supplements: Any?,var files:List<File>?,var feedback: Feedback?)

1 Answers

This seems something that the backend has to solve for you. They can give you a nullable array or just an empty array, whatever is more convenient, but implementing polymorphism is not something trivial.

Jackson makes polymorphism easier than Gson, however, it is always required some kind of anchor to know how to route the parsing, in this case, you don't have any.

Jackson uses an annotation and there you have indicate in which thing is going to pivot:

@JsonSubTypes.Type(value = Nothing.class, name = "????")

With Gson you have to implement your own JsonDeserializer but again, how do you know what type is it? If it can be cast to array then is nothing? Just writing that seems like an antipattern.

Related