Gson自动初始化并避免空例外 [英] Gson, auto-initialize and avoid null exceptions
问题描述
class Foo {int id;列表与LT;字符串>项目;列表与LT;长>日期;}
我怎么能自动初始化反序列化后为空的字段。 foo foo = new Gson()。fromJson({\id \:\test \,\items\:[1234,1235,1336]},Foo.class)
foo.dates.size(); - > 0而不是空指针异常
我知道我可以做if(foo.attr == null)foo。 attr = ...
但是我正在寻找更多的泛型代码,而没有Foo类的知识
thx
edit :对不起,只要把Getters放在Foo就足够了
关闭
您需要创建您的自定义反序列化器。
假设您的类名为 MyAwesomeClass
,你实现类似于
MyAwesomeClassDeserializer实现了JsonDeserializer< MyAwesomeClass> {
@Override
public MyAwesomeClass反序列化(JsonElement json,类型typeOfT,JsonDeserializationContext ctx)抛出JsonParseException
{
// TODO:在这里做null-magic
}
并使用GSON进行注册,如下所示:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ g $ g $ g $ g $ g $ g $ g $ );
现在,您只需调用fromJson(String,TypeToken)的
方法,以获得反序列化的对象。
MyAweSomeClass instance = gson.fromJson(json,new TypeToken< MyAwesomeClass> (){}的getType())。
when deserializing a json into a class Foo{int id; List<String> items; List<Long> dates;}
How could I auto initialize fields that are null after deserialization. Is there such a possiblity with Gson lib?
ex:
Foo foo = new Gson().fromJson("{\"id\":\"test\", \"items\":[1234, 1235, 1336]}", Foo.class)
foo.dates.size(); -> 0 and not null pointerException
I know I could do if (foo.attr == null) foo.attr = ...
but I'm looking for more generic code, without knowledge of Foo class
thx
edit: sorry just putting Getters in Foo is enough
closed
You need to create your custom deserializer.
Assuming your class is called MyAwesomeClass
, you implement something like
MyAwesomeClassDeserializer implements JsonDeserializer<MyAwesomeClass> {
@Override
public MyAwesomeClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException
{
// TODO: Do your null-magic here
}
and register it with GSON, like this:
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyAwesomeClass.class, new MyAwesomeClassDeserializer())
.create();
Now, you just call a fromJson(String, TypeToken)
method, to get your deserialized object.
MyAweSomeClass instance = gson.fromJson(json, new TypeToken<MyAwesomeClass>(){}.getType());
这篇关于Gson自动初始化并避免空例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!