Is there a way to get GSON to recognise \"False\" as a boolean?
e.g.
gson.fromJson(\"False\",Boolean.class)
Yes, you can provide your own deserializer and do whatever you wish:
public class JsonBooleanDeserializer implements JsonDeserializer<Boolean>{
@Override
public Boolean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
String value = json.getAsJsonPrimitive().getAsString();
return value.toLowerCase().equals("true");
} catch (ClassCastException e) {
throw new JsonParseException("Cannot parse json date '" + json.toString() + "'", e);
}
}
}
you then add this Deserializer to your GSON parser:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new JsonBooleanDeserializer());
Gson gson = builder.create();
gson.fromJson(result, Boolean.class);
GSON needs to know somehow that this IS a boolean, so it only works when you provide the base class (Boolean.class). It works too when you put your whole value object class into it and there is a boolean somewhere inside it:
public class X{ boolean foo; } will work with the JSON {foo: TrUe}