如何自定义 java 对象的序列化

How to customize serializing of java object

如何序列化该对象。但只有对象 anotherObject 的字段但没有 "anotherObject" 键 json

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

class B{
    int someB = 2;
}

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

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

添加到您的class方法

int getAnotherSome() {
  return anotherObject.someB
}

并注释

@JsonIgnore
B anotherObject = new B();

这应该可以解决问题

您可以使用 @JsonUnwrapped 注释。

class A {
    @JsonProperty
    int some = 1;

    @JsonUnwrapped
    B anotherObject = new B();
}

class B {
    @JsonProperty
    int someB = 2;
}