How to parse polymorphic JSON? #118
-
I have an API that returns 2 different JSON. I'm using retrofit in Java, How can I parse this? How do I create a Java class to represent it? {
"status": "running",
"result": "result info"
} in case of Error: {
"error": "Error Code"
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 8 replies
-
Have a look at JsonTypeInfo annotation - plenty of blogs and stackoverflow entries about it - eg https://www.baeldung.com/jackson-annotations The JSON will need a type field to specify which class the message relates to. An alternative non-polymorphic approach is to load the JSON as an AST and check for the existence of the 'error' field and then to deserialize the AST as an Error instance, otherwise deserialize as a Status/Result instance. See the 'readTree' section in https://www.baeldung.com/jackson-object-mapper-tutorial |
Beta Was this translation helpful? Give feedback.
-
+1 for @pjfanning's answer. In addition, mode of https://www.baeldung.com/jackson-deduction-based-polymorphism (see paragraph 3, "Deduction-based Polymorphism") |
Beta Was this translation helpful? Give feedback.
-
Can you guys please provide a link to example app / codebase i can follow along? I find it a lot complicated and it would help if I can follow a working example. Like the Github API Auth is a good example for polymorphic json. It returns different json for auth cases. |
Beta Was this translation helpful? Give feedback.
+1 for @pjfanning's answer. In addition, mode of
use = Id.DEDUCTION
would probably work well for this particular case -- it does not use explicit type id but bases it on "unique properties" found. An article that explains this is:https://www.baeldung.com/jackson-deduction-based-polymorphism
(see paragraph 3, "Deduction-based Polymorphism")