GSON假大写 [英] GSON False uppercase

查看:614
本文介绍了GSON假大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让GSON识别假作为一个布尔?

例如

  gson.fromJson(假,Boolean.class)


解决方案

是的,你可以提供自己的解串器,做任何你希望:

公共类JsonBooleanDeserializer实现JsonDeserializer<布尔> {
    @覆盖
    公共布尔反序列化(JsonElement JSON,类型typeOfT,JsonDeserializationContext上下文)
            抛出JsonParseException {
        尝试{
            字符串值= json.getAsJsonPrimitive()符getAsString()。
            返回value.toLowerCase()等于(真)。
        }赶上(抛出ClassCastException E){
            抛出新JsonParseException(无法解析JSON日期+ json.toString()+',E);
        }
    }
}

您那么这个解串器添加到您的GSON解析器:

GsonBuilder建设者=新GsonBuilder();
builder.registerTypeAdapter(Boolean.class,新JsonBooleanDeserializer());
GSON GSON = builder.create();
gson.fromJson(结果,Boolean.class);

GSON需要以某种方式,这是一个布尔知道,所以当你提供的基类(Boolean.class)它才会起作用。
它的工作原理太当你把你的整个价值对象类进去,有一个布尔地方在里面:

公共类X {布尔富; } 将与JSON的 {foo的工作:TRUE}

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}

这篇关于GSON假大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆