GSON False uppercase

后端 未结 1 504
粉色の甜心
粉色の甜心 2021-01-27 09:37

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

e.g.

gson.fromJson(\"False\",Boolean.class)
相关标签:
1条回答
  • 2021-01-27 10:17

    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 讨论(0)
提交回复
热议问题