Search code examples
javajsongsonmarshalling

How to skip null values in json text produced by gson, if TypeAdapter converts null-value?


I created a TypeAdapter for the Type Instant by writing milliseconds. How can I handle the case of the instant-field to be null. I do not want to write a kind of special entry like -1L, which I later could convert to null during reading (see example below). I want to skip the entry in the produced json-text as it is the default case.

Example:

gsonBuilder.registerTypeAdapter(Instant.class, new TypeAdapter<Instant>(){
            @Override
            public void write(final JsonWriter jsonWriter, final Instant instant) throws IOException {
                if (instant != null) {
                    jsonWriter.value(instant.toEpochMilli());
                } else {
                    jsonWriter.value(-1L);
                }
            }

            @Override
            public Instant read(final JsonReader jsonReader) throws IOException {
                long millisEpoch = jsonReader.nextLong();
                if (millisEpoch == -1) {
                    return null;
                } else {
                    return Instant.ofEpochMilli(millisEpoch);
                }
            }
        });

Solution

  • It's easy, I think you can modify your TypeAdapter to check if the instant value is null and not write it to the JSON output

    let me explain with a simple example, first, in write method, I check if the Instant value is null and write a null value instead of the epoch milliseconds, that will skip the null value in the JSON output and in the read method, I still check for the special case of -1L to convert it to null

    gsonBuilder.registerTypeAdapter(Instant.class, new TypeAdapter<Instant>() {
        @Override
        public void write(final JsonWriter jsonWriter, final Instant instant) throws IOException {
            if (instant != null) {
                jsonWriter.value(instant.toEpochMilli());
            } else {
                jsonWriter.nullValue();
            }
        }
    
        @Override
        public Instant read(final JsonReader jsonReader) throws IOException {
            long millisEpoch = jsonReader.nextLong();
            if (millisEpoch == -1) {
                return null;
            } else {
                return Instant.ofEpochMilli(millisEpoch);
            }
        }
    });
    

    good luck!