Sweety Bertilla
Sweety Bertilla

Reputation: 1032

GSON parsing for values boolean and string

I may get a json response as

"contentId": "1234",
    "events": [{
        "value": "night"
    }]

and sometimes I get as 

"contentId": "1235",
    "events": [{
        "value": true
    }]

I am using GSON parsing ,

 @Expose
    private Boolean value;

  public Boolean getValue() {
        return value;
    }

    public void setValue(Boolean value) {
        this.value = value;
    }

how would I get the string? I want to parse both the string and boolean, but both have the same name "value". How can I do both the parsing?

Upvotes: 1

Views: 1700

Answers (1)

shyam
shyam

Reputation: 1388

Assuming that you get the value inside all "value" as a String in Java code, you could use the following:

boolean myVal;
if (valueFromJson.equals("true")) {
    myVal = true;
    // implement whatever logic here which uses value as boolean type
} else if (valueFromJson.equals("false")) {
    myVal = false;
    // implement whatever logic here which uses value as boolean type
} else {
    // use logic where you need the String value
}

Note: This ofcourse assumes that the value of the String will never be "true" or "false" to work.

Upvotes: 1

Related Questions