我在努力学习Gson,我在与场排除作斗争。这是我的课程

public class Student {    
  private Long                id;
  private String              firstName        = "Philip";
  private String              middleName       = "J.";
  private String              initials         = "P.F";
  private String              lastName         = "Fry";
  private Country             country;
  private Country             countryOfBirth;
}

public class Country {    
  private Long                id;
  private String              name;
  private Object              other;
}

我可以使用GsonBuilder,并为字段名如firstName或country添加一个ExclusionStrategy,但我似乎无法排除某些字段的属性,如country.name。

使用方法public boolean shouldSkipField(FieldAttributes fa), FieldAttributes不包含足够的信息来匹配像country.name这样的过滤器。

附注:我想避免使用注释,因为我想改进这一点,并使用RegEx过滤字段。

编辑:我试着看看是否有可能模拟Struts2 JSON插件的行为

使用Gson

<interceptor-ref name="json">
  <param name="enableSMD">true</param>
  <param name="excludeProperties">
    login.password,
    studentList.*\.sin
  </param>
</interceptor-ref>

编辑: 我重新提出这个问题,补充如下:

我添加了第二个具有相同类型的字段,以进一步澄清这个问题。基本上我想要排除country。name而不是countrofbirth。name。我也不想把Country排除在外。 所以类型是一样的我想要精确定位和排除的对象图中的实际位置。


当前回答

Nishant提供了一个很好的解决方案,但还有更简单的方法。简单地用@Expose注释标记所需的字段,例如:

@Expose private Long id;

省略您不想序列化的任何字段。然后按如下方式创建你的Gson对象:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

其他回答

在kotlin中可以使用@Transient忽略字段…如。

data class MyClass{
@Transient var  myVar: Boolean
//....
}

我遇到了这个问题,在这个问题中,我只想从序列化中排除少量字段,所以我开发了一个相当简单的解决方案,使用带有自定义排除策略的Gson的@Expose注释。

使用@Expose的唯一内置方法是设置GsonBuilder.excludeFieldsWithoutExposeAnnotation(),但正如名称所示,没有显式@Expose的字段将被忽略。由于我只有几个想要排除的字段,我发现将注释添加到每个字段非常麻烦。

实际上,我想要的是相反的,其中所有内容都包括在内,除非我显式地使用@Expose来排除它。我使用了以下排除策略来实现这一点:

new GsonBuilder()
        .addSerializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                final Expose expose = fieldAttributes.getAnnotation(Expose.class);
                return expose != null && !expose.serialize();
            }

            @Override
            public boolean shouldSkipClass(Class<?> aClass) {
                return false;
            }
        })
        .addDeserializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                final Expose expose = fieldAttributes.getAnnotation(Expose.class);
                return expose != null && !expose.deserialize();
            }

            @Override
            public boolean shouldSkipClass(Class<?> aClass) {
                return false;
            }
        })
        .create();

现在,我可以很容易地用@Expose(serialize = false)或@Expose(deserialize = false)注释排除一些字段(注意,这两个@Expose属性的默认值都是true)。当然,您可以使用@Expose(serialize = false, deserialize = false),但是通过声明字段transient(使用这些自定义排除策略仍然有效)可以更简洁地实现这一点。

在阅读了所有可用的答案后,我发现,对我来说,最灵活的方法是使用自定义的@Exclude注释。所以,我为此实现了简单的策略(我不想使用@Expose标记所有字段,也不想使用与app Serializable序列化冲突的transient):

注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Exclude {
}

策略:

public class AnnotationExclusionStrategy implements ExclusionStrategy {

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return f.getAnnotation(Exclude.class) != null;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}

用法:

new GsonBuilder().setExclusionStrategies(new AnnotationExclusionStrategy()).create();

Kotlin的@Transientannotation显然也能做到这一点。

data class Json(
    @field:SerializedName("serialized_field_1") val field1: String,
    @field:SerializedName("serialized_field_2") val field2: String,
    @Transient val field3: String
)

输出:

{"serialized_field_1":"VALUE1","serialized_field_2":"VALUE2"}

我只是把@Expose注释放在这里,这里是我使用的版本

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

在Model类中:

@Expose
int number;

public class AdapterRestApi {

在Adapter类中:

public EndPointsApi connectRestApi() {
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(90000, TimeUnit.SECONDS)
            .readTimeout(90000,TimeUnit.SECONDS).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ConstantRestApi.ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    return retrofit.create  (EndPointsApi.class);
}