0

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:

image

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

    }
}```
Tomasz Kubat
  • 102
  • 2
  • 11
  • I don't use this api, but you should probably be following bean conventions: your class should have an empty() ctor and probably create its own instances of `Address` and `Description` (which can be used or *replaced* as necessary) – g00se Jun 19 '23 at 11:26
  • Maybe related to https://stackoverflow.com/questions/21626690/gson-optional-and-required-fields – Marcono1234 Jun 19 '23 at 21:21
  • 1
    Could you please explain a bit more in detail what you want to achieve? For example should a default `Description` be set? But if so, what should be the values of its fields? Isn't it cleaner that a missing field has the value `null` instead of a default value? Then your application can handle missing values in some proper way. Otherwise your application cannot properly differentiate between a default value for a missing field, and a field value which is present in JSON but which happens to be the same as the default value. – Marcono1234 Jun 19 '23 at 21:25
  • @Marcono1234 I have updated an example code. I would like to serialize data, but during my custom serialization error occur, when nested field is missing - I got NullPointerException. I am looking for an elegant, an possibly generic way to solve nulls. For me missing value is accepted, but I would like to handle it. I will have more similar classes for serialization/deserialization. – Tomasz Kubat Jun 21 '23 at 08:50
  • 1
    [This](https://stackoverflow.com/questions/42523266/gson-serialization-exclude-some-fields-if-null-but-not-all-of-them) could be of interest – g00se Jun 21 '23 at 09:09
  • I believe you over-coplicated things. Do you have to use Gson? I use Json-Jackson, and with that library I can provide you almost one liner solution. I believe that with gson you also can do much simpler solution. I just don't have experience with Gson as much – Michael Gantman Jun 21 '23 at 09:17

0 Answers0