根据GSON中的值排除序列化中的某些字段 [英] Excluding certain fields from Serialization based on value in GSON
问题描述
实现此目的的方法是通过为有问题的类创建自定义序列化程序。在允许Gson以默认方式创建JSON对象后,根据其值删除要排除的属性。
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);
}
返回jObj;
$ b 在Gson对象中注册新的序列化程序用于序列化这个类的应用程序。
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(MyClass.class,new SerializerForMyClass());
Gson gson = gsonBuilder.create();
gson.toJson(myObjectOfTypeMyClass);
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?
解决方案 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);
这篇关于根据GSON中的值排除序列化中的某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!