根据GSON中的值排除序列化中的某些字段 [英] Excluding certain fields from Serialization based on value in GSON

查看:731
本文介绍了根据GSON中的值排除序列化中的某些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用GSON进行序列化的目的是,我没有找到一种排除某些字段序列化的方法,它基于由Gson提供的基于字段值的ExclusionStrategy类,因为它只支持基于顶级类或字段属性的排除。字段属性不包含该字段的值。所以我该怎么做?

解决方案

实现此目的的方法是通过为有问题的类创建自定义序列化程序。在允许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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆