Solx85 Solx85 - 3 years ago 157
Java Question

Gson deserialize boolean from 1 to false in JAVA Android

The class I am using as follow:

public class TheJob {
private String jobDescription = null, jobAdditionalInfo = null, jobAddress = null;

public boolean jobActive = true;

public boolean offsiteAllowed;

The JSON I receive as follow:

[{"jobId":"2","jobDescription":"Beta","jobAdditionalInfo":"Edited ","jobAddress":"103 Emus Avenue \nCenturion \n0157 \nSouth Africa \n","jobActive":"1","offsiteAllowed":"1"}]

I have removed the rest of the JSON array items since they are exactly the same.

I cannot get the boolean fields jobActive and offsiteAllowed to parse correctly, they always parse false even though the JSON value is 1.

Everything else in my TheJob class de-serialises perfectly except the booleans

Any suggestions would be greatly appreciated.

Answer Source

Gson is very type oriented. To parse an int value as boolean you might have to register a custom boolean deserialization class. Alternatively if you are in control of the api change return to true rather than 1. It's expecting 'true' and treating everything else as false. There should be a few examples of registering a custom JsonDeserializer class. This adapter would allow you to do things like deserialize into a boolean variable called isFruit and return Apple, Orange, Carrot etc from API. Once registered you could implement the custom deserializer to evaluate the value and deserialize true and false into isFruit as needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download