I am using gson to deserialize/serialize data. Currently I use simple deserialization to just get the json data to pojo representation as is. Next I use custom serialization to parse json output.
I have some problems with nested fields. When the json data has some missing nested field I am unable to access them in the Serialization step, with NullPointerException error. Example - I have an address nested field, which can contains of city, zipcode and so on. If the incoming json has no address
field, I got NullPointerException
when accerssing address.city
.
As a result, if some json field are missing, I just want to populate missing values as output in serrialization, but I would like to add a reasonable null error handling. No obligatory checks are required.
myCustomer pojo example:
import com.google.gson.*;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.Date;
public class MyGsonTest {
// my deserialization class
class MyCustomer {
// fields
String id;
String name;
Date birthdate;
// nested fields
Address address;
Description description;
class Address {
String city;
String zipCode;
Street street;
// nested fields can have multiple in-depth levels, but I have simplified it for the presentation purposes
class Street {
String apartment;
String number;
}
}
class Description {
String info;
String moreInfo;
}
}
// my custom deserialization class
public class MyCustomerSerializer implements JsonSerializer<MyCustomer> {
@Override
public JsonElement serialize(MyCustomer myCustomer, Type type, JsonSerializationContext jsonSerializationContext) {
// create initial/empty JsonObject
JsonObject jo = new JsonObject();
// next add some properties...
// ok - we access created/deserialized nested field
jo.addProperty("city", myCustomer.address.city);
jo.addProperty("zipcode", myCustomer.address.zipCode); // ok iven if underlying field is missing
/*
!!!
NullPointerException - deserialized nested field is null (no leaf-level fields)
!!!
*/
jo.addProperty("info", myCustomer.description.info);
jo.addProperty("moreInfo", myCustomer.description.moreInfo);
return jo;
}
}
@Test
public void testRun() {
// create gson instance with gson builder
GsonBuilder gsonBuilder = new GsonBuilder()
// register custom deserializer for MyCustomer class
.registerTypeAdapter(MyCustomer.class, new MyCustomerSerializer());
Gson gson = gsonBuilder.create();
// get example data
// missing: 'city.zipCode' and entire 'description'
String myCustomer1String = "{'id':'a123','name':'John','birthdate':'1987-01-01','address':{'city':'Colorado'}}";
// deserialize - create customer pojo instance
MyCustomer myCustomer = gson.fromJson(myCustomer1String, MyCustomer.class);
// serialization - error occur here
String myCustomerParsed = gson.toJson(myCustomer);
}
}```