Gson deserializes boolean values from 1 to false in Java Android
The class I’m using is as follows:
public class TheJob {
private String jobDescription = null, jobAdditionalInfo = null, jobAddress = null;
@SerializedName("jobActive")
public boolean jobActive = true;
@SerializedName("offsiteAllowed")
public boolean offsiteAllowed;
}
The JSON I received is as follows:
[{"jobId":"2","jobDescription":"Beta","jobAdditionalInfo":"Edited ","jobAddress":"103 Emus Avenue \nCenturion \n0157 \nSouth Africa \n","jobActive":"1"," offsiteAllowed":"1"}]
I’ve removed the rest of the JSON array items because they’re exactly the same.
I can’t parse the boolean fields jobActive and offsiteAllowed correctly, they always resolve to false, even if the JSON value is 1.
Everything else in my TheJob class is perfectly deserialized except for the boolean value
Any suggestions would be appreciated.
Solution
GSON is very type-oriented. To resolve an int value to a boolean value, you might have to register a custom boolean value deserialization class. Or, if you control API changes, return true instead of 1. It expects “true” and treats everything else as false. There should be some examples of registering a custom JsonDeserializer class. This adapter will allow you to do things like deserialize into a boolean variable called isFruit and return Apple, Orange, Carrot, etc. from the API. Once registered, you can implement a custom deserializer to evaluate values and deserialize true and false to isFruit as needed.