Gson, automatically initialize and avoid null exceptions

when json is deserialized in class Foo{int id; List<String> items; List<Long> dates;} class Foo{int id; List<String> items; List<Long> dates;} class Foo{int id; List<String> items; List<Long> dates;} How can I automatically initialize fields that are null after deserialization. Is there such a possibility with Gson lib?

Example:

 Foo foo = new Gson().fromJson("{\"id\":\"test\", \"items\":[1234, 1235, 1336]}", Foo.class) foo.dates.size(); -> 0 and not null pointerException 

I know what I could do if (foo.attr == null) foo.attr = ...
but I'm looking for more general code without knowing the Foo class
THX

edit: sorry just put getters in foo


closed

+4
source share
1 answer

You need to create your own 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 using GSON, for example:

 Gson gson = new GsonBuilder() .registerTypeAdapter(MyAwesomeClass.class, new MyAwesomeClassDeserializer()) .create(); 

Now you just call the fromJson(String, TypeToken) method to get your deserialized object.

 MyAweSomeClass instance = gson.fromJson(json, new TypeToken<MyAwesomeClass>(){}.getType()); 
0
source

All Articles