首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@JsonIgnore vs @瞬态-difference?

@JsonIgnore vs @瞬态-difference?
EN

Stack Overflow用户
提问于 2015-04-21 03:23:53
回答 3查看 21.4K关注 0票数 24

哪一个用于跳过字段以进行序列化和反序列化。

@JsonIgnore如果@瞬态也跳过序列化和反序列化过程中的字段,我们为什么要使用它?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-04-21 03:43:19

两者之间的明显区别在于,如果将@Transient标记为@Transient,则将其作为JPA的一部分来忽略字段的持久化。

其中,@JsonIgnore只用于忽略被序列化的标记字段,以及与JSON之间的反序列化。

这意味着标记为@JsonIgnore的字段仍然可以持久化在JPA持久性中,其中标记为@Transient的字段既不会被持久化,也不会被序列化、反序列化。

票数 35
EN

Stack Overflow用户

发布于 2019-10-31 17:54:36

我们应该区分javax.persistence.Transientjava.beans.Transient。正如@shazin和@Abhishek Kumar所提到的,前者指示JPA忽略该属性以保持持久性,并且不影响编组。杰克逊在编组过程中将后者与JsonIgnore一样对待,就像在JacksonAnnotationIntrospector#_isIgnorable(Annotated)中看到的那样。

代码语言:javascript
复制
protected boolean _isIgnorable(Annotated a)
{
    JsonIgnore ann = _findAnnotation(a, JsonIgnore.class);
    if (ann != null) {
        return ann.value();
    }
    if (_java7Helper != null) {
        Boolean b = _java7Helper.findTransient(a);
        if (b != null) {
            return b.booleanValue();
        }
    }
    return false;
}

Java7SupportImpl#findTransient(Annotated)正在寻找java.beans.Transient

票数 3
EN

Stack Overflow用户

发布于 2019-11-14 19:58:02

@Transient是Java中transient关键字的寓言词。当与变量一起使用时,它从未被序列化。

示例:

代码语言:javascript
复制
public class Person {
    String name;
    int age;
    String password;

    public Person(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Transient
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

public void serializationTest() throws JsonProcessingException {

    Person aPerson = new Person("Demonte", 37, "bestKeptSecret1995");
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(aPerson);

    System.out.println(json);
}

通过注释getPassword() (请记住用于序列化的getter),@Transient将生成

代码语言:javascript
复制
{"name":"Demonte","age":37}

现在,如果您重新查看Person类代码并删除@Transient并将transient添加到password变量中,并且还向杰克逊映射程序添加了一个特性,以告诉它如何处理标记为transient的字段

代码语言:javascript
复制
transient String password;

代码语言:javascript
复制
mapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);

(请记住,Jackson直接使用getters而不是成员进行序列化),那么您将得到相同的输出。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29762328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档