Gson, auto-initialize and avoid null exceptions

陌路散爱 提交于 2019-12-13 13:29:20

问题


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


回答1:


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());


来源:https://stackoverflow.com/questions/11407541/gson-auto-initialize-and-avoid-null-exceptions

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