GSON相当于Jackson中的@JsonIgnoreProperties [英] GSON equivalent for @JsonIgnoreProperties in Jackson
问题描述
在杰克逊你可以通过在类级别注释 @JsonIgnoreProperties
来忽略属性,并且不在实际JSON中的属性不会从/到序列化/反序列化Java类。如果我们使用GSON,它的等价物是什么?
您可以使用GSON @Expose
使用 GsonBuilder.excludeFieldsWithoutExposeAnnotation()
。
p>
public class User {
@Expose private String firstName;
@Expose(serialize = false)private String lastName;
@Expose(serialize = false,deserialize = false)private String emailAddress;
私人字符串密码;如果您使用 Gson gson = new GsonBuilder(),那么您可以使用$ g
$ b < .excludeFieldsWithoutExposeAnnotation().create()
与上面的类,然后 toJson()
和 fromJson() code>方法将完全忽略密码字段,因为它没有 @Expose
注释。
(请注意,您也可以在此处获得更细致的控制,因为您可以控制GSON是否序列化/反序列化字段)。
参考: https:// github.com/google/gson/blob/master/UserGuide.md#TOC-Gson-s-Expose
In Jackson you can ignore the properties by giving annotation @JsonIgnoreProperties
at class level and the properties which are not in the actual JSON are not serialized/deserialized from/to the Java class. What is the equivalent of it if we are using GSON?
解决方案 You can get a similar effect with the GSON @Expose
annotation using GsonBuilder.excludeFieldsWithoutExposeAnnotation()
.
E.g.
public class User {
@Expose private String firstName;
@Expose(serialize = false) private String lastName;
@Expose (serialize = false, deserialize = false) private String emailAddress;
private String password;
}
If you use Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
with the above class, then the toJson()
and fromJson()
methods will completely ignore the password field as it doesn't have an @Expose
annotation.
(Note you also get finer-grained control here as you can control whether GSON serializes/deserializes fields as well).
Reference: https://github.com/google/gson/blob/master/UserGuide.md#TOC-Gson-s-Expose
这篇关于GSON相当于Jackson中的@JsonIgnoreProperties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!