【问题标题】:How to customize serializing of java object [duplicate]如何自定义java对象的序列化[重复]
【发布时间】:2019-08-06 09:37:03
【问题描述】:

如何序列化该对象。但只有对象 anotherObject 的字段,但 json 中没有“anotherObject”键

class A{
   int some = 1;
   B anotherObject = new B();
}

class B{
    int someB = 2;
}

我需要下一个 JSON 作为序列化结果

{
    "A":{
       some: 1,
       anotherSome: 2
    }
}

【问题讨论】:

  • 您能否详细说明 anotherObject 与 anotherSome?

标签: java jackson fasterxml


【解决方案1】:

你可以使用@JsonUnwrapped注解。

class A {
    @JsonProperty
    int some = 1;

    @JsonUnwrapped
    B anotherObject = new B();
}

class B {
    @JsonProperty
    int someB = 2;
}

【讨论】:

    【解决方案2】:

    给你的类添加一个方法

    int getAnotherSome() {
      return anotherObject.someB
    }
    

    并标注

    @JsonIgnore
    B anotherObject = new B();
    

    这应该可以解决问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-03
      • 2015-04-25
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      相关资源
      最近更新 更多