开发者

GSON False uppercase

Is there a way to get GSON to recognise "False" as a boolean?

e.g开发者_StackOverflow中文版.

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}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜