【问题标题】:Jackson: Serializing Map<Object, BigDecimal> yields undesired object referenceJackson:序列化 Map<Object, BigDecimal> 会产生不需要的对象引用
【发布时间】:2021-12-08 17:03:29
【问题描述】:

假设我正在尝试用 Jackson 序列化以下内容:

public class Investment implements Serializable{
   private String shortName;
   private MutualFund mutualFund;

   public String getShortName() {
       return shortName;
   }

   public void setShortName(String shortName) {
       this.shortName = shortName;
   }

   public MutualFund getMutualFund() {
      return mutualFund;
   }

   public void setMutualFund(MutualFund mutualFund) {
      this.mutualFund = mutualFund;
   }
}

那又是指:

public class MutualFund implements Serializable{
   private BigDecimal expenseRatio;
   private Map<Investment, BigDecimal> underlyingInvestments;

   public BigDecimal getExpenseRatio() {
      return BigDecimalHelper.guard(expenseRatio);
   }

   public void setExpenseRatio(BigDecimal expenseRatio) {
      this.expenseRatio = expenseRatio;
   }

   public Map<Investment, BigDecimal> getUnderlyingInvestments() {
      return underlyingInvestments;
   }

   public void setUnderlyingInvestments(Map<Investment, BigDecimal> 
      underlyingFunds) {
      this.underlyingInvestments = underlyingFunds;
   }
}

当我尝试用 Jackson 序列化它时,其他一切都很好,除了我最终得到一个 Investment 对象引用,而不是像我期望的那样具有属性的字符串:

"underlyingInvestments":{"com.financial.detail.Investment@5d465e4b":1}}

我尝试设计一些自定义序列化程序,但没有成功,因为我总是获得 nested Investment(s) 的对象引用。所以,我有一个两部分的问题:

  1. 可以简单地使用 Jackson 注释解决此问题吗?
  2. 如果我必须构建一个自定义序列化程序,有人能指出我正确的方向吗? 鉴于此问题的嵌套性质(例如,一项投资可能包含一个共同基金,而该共同基金又具有一项与共同基金的投资......)

【问题讨论】:

    标签: java json serialization jackson


    【解决方案1】:

    问题是您使用对象Investment 作为 Map 的键,所以这里的问题是,您希望 json 具有哪些键? Json 键只能是字符串,因此映射器正在执行 Investment 类的 toString() 方法。如果您知道该键应该是什么,那么您可以实现该方法,如下所示:

    public class Investment implements Serializable {
            private String shortName;
            private MutualFund mutualFund;
    
            // ...
    
            @Override
            public String toString() {
                return shortName;
            }
        }
    

    这将创建一个像这样的 json 对象:

    {
        "expenseRatio": 1,
        "underlyingInvestments": {
            "shortName": 10
        }
    }
    

    另外,正如@chrylis-cautiouslyoptimistic 建议的那样,另一种选择是使用@JsonValue 来指示序列化时使用哪种方法,如下所示:

    public class Investment implements Serializable{
       private String shortName;
       private MutualFund mutualFund;
    
       @JsonValue
       public String getShortName() {
           return shortName;
       }
    
       // ...
    }
    

    【讨论】:

    • 更好用@JsonValue。
    • 好点@chrylis-cautiouslyoptimistic-,我也添加了。谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-05-19
    • 2017-05-09
    • 2014-11-12
    • 2018-08-24
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多