Improving Java / Kotlin JSON Parsing

I am using an API that gives me this type of JSON:

{ "data": { "name": "Start", "pid": "1", "position": { "data": { "x": "31", "y": "330" }, "metadata": "empty" } }, "metadata": "empty" } 

I created classes with objects with the same structure as above JSON. I use retrofit lib on Android, inside of which GSON is used to parse JSON.

My model classes will be like this:

MResponse.class

 public class MResponse { @SerializedName("data") public User user; String metadata; } 

User.class

 public class User { public String name; public String pid; @SerializedName("position") public PositionData positionData; } 

PositionData.class

 public class PositionData { @SerializedName("data") public Position position; public String metadata; } 

Position.class

 public class Position { public String x; public String y; } 

Now it works great for me. But, as you can see, for each model I have to create a parent who will have the same structure, just changes the child. This fact doubles the classes that I use for my models. I would like to ask if there is a better way to avoid all of these classes.

I do not want to use inner classes. I thought the guys who made JSON, like this, must have had a reason why they did it this way, as well as a way to facilitate parsing.

Usually I used to parse such a JSON structure:

 { "data": { "name": "Start", "pid": "1", "position": { "x": "31", "y": "330" } } } 

And here it is easier if I follow the solution above.

EDIT

Also any decision in Kotlin is welcome.

EDIT 2

The solution for Kotlin is here.

+7
java json android parsing kotlin
source share
2 answers

Well, the solution I requested was quite simple, in my opinion, I simply did not know this at the beginning.

Based on the Retrofit source code and some other related Java generics answers, this was the answer to my problem:

 public class DataResponse<T, R> { public T data; @SerializedName("meta") public R metadata; } 

and this is an example of how I can use it:

 Observable<DataResponse<User, BaseMeta>> getUser() 

For me it was a solution. If there is a better solution, I am ready to accept them.

0
source share

I do not think your request is possible. If there is a solution, then it will simply create intermediate classes that will do almost the same thing as you.

In Kotlin, I would do it like that. Feel free to even put it in a single .kt file:

 data class MResponse(@SerializedName("data") val user: User, val metadata: String) data class User(val name: String, val pid: String, @SerializedName("position") val positionData: PositionData) data class PositionData(@SerializedName("position") val position: Position, val metadata: String) data class Position(val x: String, val y: String) 
0
source share

All Articles