0

I'm using Gson with retrofit. My server accepts null values so in the gson builder I have given

gsonBuilder.serializeNulls();

So that null values will not be ignored. But in some APIs I have a special case, where some of the fields should be present even is its's null, and some other fields should not serialize if it is null.

for example If I have a request class like

class Request {
    String id;
    String type;
}

and if I have a request where id=null and type=null , gson should serialize it like:

{
    id : null
}     

Which means, if type is null it should ignore that field, but if id is null, it should present as null in the request.

Currently it is serializing like:

{
     id : null, 
     type:null
}  

since I have given gsonBuilder.serializeNulls(); . How can I deal with this special case?

Ishara Madhawa
  • 3,549
  • 5
  • 24
  • 42
doe
  • 971
  • 2
  • 11
  • 27
  • 2
    maybe duplicate https://stackoverflow.com/questions/35477267/gson-serialize-null-for-specific-class-or-field ? – Michal Jun 11 '18 at 08:15
  • Possible duplicate of [Gson Serialize field only if not null or not empty](https://stackoverflow.com/questions/18491733/gson-serialize-field-only-if-not-null-or-not-empty) – 2Dee Jun 11 '18 at 08:54

1 Answers1

1

Here is my code:

public static void main(String[] args) throws SecurityException,
            NoSuchFieldException, ClassNotFoundException {
        GsonBuilder gson = new GsonBuilder();
        Request request = new Request();
        Gson g = gson.serializeNulls()
                .setExclusionStrategies(new TestExclStrat(request)).create();
        System.out.println(g.toJson(request));
    }

class Request {
    public String id;
    public String type;
}

class TestExclStrat implements ExclusionStrategy {

    private Object obj;

    public TestExclStrat(Object obj) throws SecurityException,
            NoSuchFieldException, ClassNotFoundException {
        this.obj = obj;
    }

    public boolean shouldSkipClass(Class<?> arg0) {
        return false;
    }

    public boolean shouldSkipField(FieldAttributes f) {
        if (obj instanceof Request) {
            System.out.println(f.getName());
            if (!"id".equals(f.getName())) {
                try {
                    Field field = obj.getClass().getDeclaredField(f.getName());
                    field.setAccessible(true);
                    if (field.get(obj) == null) {
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

}
Duong Anh
  • 529
  • 1
  • 4
  • 21