GSON False uppercase

◇◆丶佛笑我妖孽 提交于 2019-12-20 07:15:11

问题


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

e.g.

gson.fromJson("False",Boolean.class)

回答1:


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}



来源:https://stackoverflow.com/questions/4722773/gson-false-uppercase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!