GSON equivalent for @JsonIgnoreProperties in Jackson
在Jackson中,您可以通过在类级别提供注释@JsonIgnoreProperties来忽略属性,并且不在Java类中对未在实际JSON中的属性进行序列化/反序列化。 如果我们使用GSON,那相当于什么?
使用GsonBuilder.excludeFieldsWithoutExposeAnnotation()使用GSON @Expose批注可以得到类似的效果。
例如。
1 2 3 4 5 6
| public class User {
@Expose private String firstName ;
@Expose (serialize = false) private String lastName ;
@Expose (serialize = false, deserialize = false) private String emailAddress ;
private String password ;
} |
如果将Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()与上述类一起使用,则toJson()和fromJson()方法将完全忽略密码字段,因为它没有@Expose批注。
(请注意,在这里您还可以获得更细粒度的控制,因为您还可以控制GSON是否对字段进行序列化/反序列化)。
参考:https://github.com/google/gson/blob/master/UserGuide.md#TOC-Gson-s-Expose
-
是的,但是它的工作原理相反,如果我必须排除数百个字段中的一个,那就不太舒服了。
在GSON中,您也可以将字段声明为transient。与将其他字段标记为@Expose的效果相同。但是,您将不会像@Expose那样对序列化/反序列化有更精细的控制。但是,如果您有100个跨多个类的字段,并且只需要排除一个字段,则将字段标记为transient会更加方便。此外,这适用于GSON的默认设置。例如。
1 2 3 4 5 6
| public class User {
String firstName ;
String lastName ;
private String emailAddress ;
private transient String password ;
} |
参考:https://github.com/google/gson/blob/master/UserGuide.md#finer-points-with-objects