Gson:如何在没有注释的情况下从序列化中排除特定字段 [英] Gson: How to exclude specific fields from Serialization without annotations

查看:29
本文介绍了Gson:如何在没有注释的情况下从序列化中排除特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 Gson,但我正在努力解决字段排除问题.这是我的课程

I'm trying to learn Gson and I'm struggling with field exclusion. Here are my classes

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 并为 firstNamecountry 等字段名称添加 ExclusionStrategy,但我似乎无法排除某些字段的属性,例如 <代码>国家/地区名称.

I can use the GsonBuilder and add an ExclusionStrategy for a field name like firstName or country but I can't seem to manage to exclude properties of certain fields like country.name.

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

Using the method public boolean shouldSkipField(FieldAttributes fa), FieldAttributes doesn't contain enough information to match the field with a filter like country.name.

P.S:我想避免使用注释,因为我想对此进行改进并使用 RegEx 过滤字段.

P.S: I want to avoid annotations since I want to improve on this and use RegEx to filter fields out.

编辑:我想看看是否可以模拟 Struts2 JSON 插件

Edit: I'm trying to see if it's possible to emulate the behavior of Struts2 JSON plugin

使用 Gson

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

我通过以下补充重新打开了这个问题:

I reopened the question with the following addition:

我添加了第二个相同类型的字段以进一步阐明这个问题.基本上我想排除 country.name 而不是 countrOfBirth.name.我也不想排除 Country 作为一种类型.所以类型是相同的,它是我想要查明和排除的对象图中的实际位置.

I added a second field with the same type to futher clarify this problem. Basically I want to exclude country.name but not countrOfBirth.name. I also don't want to exclude Country as a type. So the types are the same it's the actual place in the object graph that I want to pinpoint and exclude.

推荐答案

任何你不希望序列化的字段通常你应该使用transient"修饰符,这也适用于 json 序列化器(至少它适用于我用过的几个,包括 gson).

Any fields you don't want serialized in general you should use the "transient" modifier, and this also applies to json serializers (at least it does to a few that I have used, including gson).

如果您不想在序列化的 json 中显示名称,请给它一个瞬态关键字,例如:

If you don't want name to show up in the serialized json give it a transient keyword, eg:

private transient String name;

Gson 文档中的更多详细信息

这篇关于Gson:如何在没有注释的情况下从序列化中排除特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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