Excluding certain fields from Serialization based on value in GSON

前端 未结 3 907
夕颜
夕颜 2020-12-28 23:01

I am using GSON for my serialization purposes, I am not finding a way of excluding certain fields from serialization based on ExclusionStrategy class provided by Gson based

3条回答
  •  天命终不由人
    2020-12-28 23:09

    The way to achieve this is by creating custom serializer for the class in question. After allowing Gson to create a JSON object in default fashion, remove the property that you want to exclude based on its value.

    public class SerializerForMyClass implements JsonSerializer {  
    
        @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 registering the new serializer in the Gson object that you use for serialization in the application for this class.

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(MyClass.class, new SerializerForMyClass());
    Gson gson=gsonBuilder.create();
    gson.toJson(myObjectOfTypeMyClass);
    

提交回复
热议问题