How can I configure Gson to skip serialization of enum values if they are null?

33 views
Skip to first unread message

Yeikel Santana

unread,
Apr 30, 2020, 1:24:56 PM4/30/20
to google-gson
I am using open api to generate my model files , running the following snippet : 

java -jar -Dmodels \
-DmodelDocs=false
-DmodelTests=false openapi-generator-cli-4.3.0.jar \
generate
-i swagger.yaml -g java --model-package=c
models
--additional-properties dateLibrary=java8-localdatetime,useBeanValidation=true,hideGenerationTimestamp=true \
--output=../../../



When I use open api generator, it generates the following TypeAdapter for my enum.

public static class Adapter extends TypeAdapter<CodesEnum> {
     
@Override
     
public void write(final JsonWriter jsonWriter, final CodesEnum enumeration) throws IOException {
        jsonWriter
.value(enumeration.getValue());
     
}



My CodesEnum are optional in my schema, so they can be
null

. Issue is that we I try to serialize the object using toJson, for cases when enumeration is null , it generates a null pointer exception.

String json = GSON.toJson(request);


java
.lang.NullPointerException
    models
.Type$CodesEnum$Adapter.write(Type.java:222)


How can I configure Gson to that it skips the call to
.write

all together?



Thanks
Reply all
Reply to author
Forward
0 new messages