Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 on the value of field, as it only supports top level class or field attributes based exclusions. The field attributes do not include the value of that field. So what should I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
522 views
Welcome To Ask or Share your Answers For Others

1 Answer

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<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 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...