A way to achieve this is to create a custom serializer for the class in question. After Gson creates the default JSON object, remove the property that you want to exclude based on its value.
public class SerializerForMyClass implements JsonSerializer<MyClass> { @Override public JsonElement serialize(MyClass obj, Type type, JsonSerializationContext jsc) { Gson gson = new Gson(); JsonObject jObj = (JsonObject)gson.toJsonTree(obj); if(obj.getMyProperty()==0){ jObj.remove("myProperty"); } return jObj; } }
And register a new serializer in the Gson object that you use to serialize in the application for this class.
GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(MyClass.class, new SerializerForMyClass()); Gson gson=gsonBuilder.create(); gson.toJson(myObjectOfTypeMyClass);
Atharva
source share