gpt4 book ai didi

java - 如何在封装设计中忽略 json 属性

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:37 26 4
gpt4 key购买 nike

class A{ 
private B b;
//other properties
//getter setter
}
// unable to add jsonIgnore in this class due to dependency in other module
class B {
int id;
String name;
String defname;
}

我想忽略由 codehaus.jackson API 构建的 A 类 JSON 中的 defname

我需要{a:{id:value,name:value}}

最佳答案

您可以使用 Mixin为此目的。

  • 首先创建一个带有JsonIgnore注解的抽象类:

    abstract class MixIn{
    @JsonIgnore
    abstract String getDefname(); }
  • 然后按如下方式使用它。 (请确保您的 B 类中 defName 字段的 getter 名称为 getDefName() 或在 Mixin 类中将其更改为您的名称。)

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixIn( B.class, MixIn.class );
    objectMapper.writeValue( System.out, new A() );

这打印:

{"b":{"id":1,"name":"Sercan"}}

关于java - 如何在封装设计中忽略 json 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30255398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com