How to I deserialize different json response for the same request to different bean object
See original GitHub issuefor example, for the same request, the server may return:
{
"code":200,
"data":{
"xxx":"xxx"
}
}
or:
{
"code":666,
"error":"error detail"
}
And I’m using Android and Retrofit, so how should I handle this desrialization task?
the above question could be summarized as: how could hanndle deserialization on different condition(the json struction of response may differ)?
Or maybe should I adjust the response structure? But many 3rdparty api return stuff just like above so It’s impossible to adjust the response structure.
Issue Analytics
- State:
- Created 2 years ago
- Comments:5
Top Results From Across the Web
json deserialize in java for different type of variable in same ...
Option 1: If you know which api you are getting response from, you can have two classes, each holding expiry in format specific...
Read more >Convert JSON Response Body to Java Object - Tools QA
This tutorial explains How to convert or parse JSON Response Body to Java Object (POJO) using Deserializing in Java with examples.
Read more >Definitive Guide to Jackson ObjectMapper - Serialize and ...
In this detailed guide - learn everything you need to know about ObjectMapper. Convert JSON to and from Java POJOs, implement custom ...
Read more >Mapping a Dynamic JSON Object with Jackson - Baeldung
In this quick tutorial, we'll learn multiple ways of mapping dynamic JSON objects into Java classes. Note that in all of the tests, ......
Read more >Spring Restful Web Services Example with JSON, Jackson ...
Spring is one of the most widely used Java EE frameworks. ... to plugin JSON as request and response in method handler -->...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
You can solve this by implementing a custom
JsonDeserializer
orTypeAdapterFactory
.JsonDeserializer
parses the JSON data into an in-memory representation ofJsonElement
(and subtypes).TypeAdapterFactory
createsTypeAdapter
instances which read the JSON data from the stream and are therefore more efficient. However,TypeAdapterFactory
can only be used ifcode
is always the first member in the JSON data because its value is needed to determine how to parse the JSON data.The following uses
JsonDeserializer
:I am closing this because I think this has been answered. Please let us know if you still have questions regarding this.