Gson删除不必要的嵌套对象字段 [英] Gson remove unnecessary nested object fields

查看:183
本文介绍了Gson删除不必要的嵌套对象字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试序列化对象。我具有以下结构:

I am trying to serialize an object. I have the following structure:

Class A{
String aField1;
String aField2;
B bObj;
}
Class B{
String bField1;
String bField2;
String bField3;    
}

我正在尝试序列化A类和B类对象,以将它们发送到服务器。
当我序列化 Class A 对象时,它给了我

I am trying to serialze class A and B objects to send them to server. When I am serializing Class A object, it gives me

{
 aField1: "abc",
 aField2: "def",
 B: {
    bField1: "mnp",
    bField2: "qrt",
    bField3: "xyz",
    }
}

并序列化 Class B obj:

{
 bField1: "mnp",
 bField2: "qrt",
 bField3: "xyz",
}

但我要 Class A 对象,如下所示:

But I want Class A object like this:

{
 aField1: "abc",
 aField2: "def",
 B: {
    bField1: "mnp"
    }
}

我目前正在使用 GSON 库来完成此操作。
与服务器交互时,我想删除多余的键值对。 我该怎么做?

I am currently using GSON library to accomplish this. I want to remove extra key value pairs when interacting with server. How can I do this?

推荐答案

您可以标记 bField2 bField3 作为 transient 或使用注释 @Expose(serialize =错误)

You can mark bField2 and bField3 as transient or use the annotation @Expose(serialize = false).

或者您可以自定义序列化排除策略。

示例代码:

Or you can customize your serialization exclusion strategy.
Sample code:

GsonBuilder builder = new GsonBuilder();
Type type = new TypeToken <A>(){}.getType();
builder.addSerializationExclusionStrategy(
        new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                return fieldAttributes.getName().equals("bField2") ||
                            fieldAttributes.getName().equals("bField3");
            }
            @Override
            public boolean shouldSkipClass(Class<?> aClass) {
                return false;
            }
        }
);

这篇关于Gson删除不必要的嵌套对象字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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