【问题标题】:How to ignore json property in encapsulated design如何在封装设计中忽略 json 属性
【发布时间】:2015-05-15 08:56:19
【问题描述】:
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;
}

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

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

【问题讨论】:

    标签: java jaxb jackson encapsulation


    【解决方案1】:

    您可以为此使用Mixin

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

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

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

    打印出来:

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

    【讨论】:

    • 嘿我只能修改B类
    • 可能是我没有正确解释问题对象映射器已经写好了。并且该类扩展了其他一些类。
    • 唯一的办法是修改对象映射器,否则你必须做一个讨厌的字符串解析和删除过程,这是任何世界都不推荐的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 2011-12-08
    相关资源
    最近更新 更多