Solx85
Solx85

Reputation: 240

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;

    @SerializedName("jobActive")
    public boolean jobActive = true;

    @SerializedName("offsiteAllowed")
    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.

Upvotes: 3

Views: 2003

Answers (2)

mrahimygk
mrahimygk

Reputation: 517

The most simple way to achieve this (by hand) is to check and change the data yourself. I usually make static method in a Util class like this:

parseTypedBoolean(JsonObject obj, String... keys);

This makes it easy to parse all the Boolean values which are saved as 0's and 1's.

for (String key : keys) {
    if (obj.getInt(key) == 1) {
        obj.put(key, true);
    } else obj.put(key, false);
}

After each data fetch:

JSONObject curr = response.getJSONObject(i);
toBoolean(curr, "is_available", "is_new", "is_parsed", "is_registered" ,...);

You can have an enum for this frequently-used keys.

Upvotes: 1

Kobus Kleynhans
Kobus Kleynhans

Reputation: 126

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.

Upvotes: 2

Related Questions