Reputation: 5880
I know this might be an example of bad JSON API practice, but I am forced to handle a JSON response like this:
{
"error": "Username required."
}
but when it's not error, the error
field become a boolean:
{
"error": false
}
How to properly handle it in Gson (preferably with minimal configurations) in a clean way?
note: in the POJO I have String getErrorMessage()
and boolean isError()
Upvotes: 2
Views: 580
Reputation: 601
Something like this should do.
public class Main
{
public static void main(String args[])
{
Gson gson = new Gson();
Something s = new Something();
s.setError("Success");
System.out.println(gson.toJson(s));
s.setError(false);
System.out.println(gson.toJson(s));
}
}
Class "Something" looks:
public class Something
{
private Object error;
public Object getError()
{
return error;
}
public void setError(Object error)
{
this.error = error;
}
}
Output:
{"error":"Success"}
{"error":false}
Upvotes: 1
Reputation: 16625
Gson can't do this without you writing a custom deserialiser. The Gson Design Document includes this paragraph:
Navigating the Json tree or the target Type Tree while deserializing
When you are deserializing a Json string into an object of desired type, you can either navigate the tree of the input, or the type tree of the desired type. Gson uses the latter approach of navigating the type of the target object. This keeps you in tight control of instantiating only the type of objects that you are expecting (essentially validating the input against the expected "schema"). By doing this, you also ignore any extra fields that the Json input has but were not expected.
From this you can see that Gson will look at your object when trying to deserialise the JSON, so a change in type in the JSON document won't be considered.
What you can do is write a your own serialiser/deserialiser and register it before deserialising the document.
Upvotes: 1