通过组合来自两个类的字段来创建 JSON

我有两个班:A班,B班


class A{

 private int F1;

 private String F2;

}


class B{

 private int F3;

 private String F4;

 private String F5;

}

我想要这样的 JSON:


{

   "F1": 123

   "F2": "ABC"

   "F3": 456

   "F4": "CDE"

   "F5": "FGH"

}

我正在使用 springboot,它会在我从 @RestController 返回对象后立即创建 JSON。如何使用这两个类实现上述 json。


注意:1.)我已经知道通过使用 class A extends B ,我可以实现这一点,但我正在寻找一些基于 spring 的方法来实现这一点


2.) 在 B 类中使用 @Embeddable 然后在 A 类中创建引用会在 JSON 中创建额外的标签 B,如下所示:


{

   "F1": 123

   "F2": "ABC"

    b: {

          "F3": 456

          "F4": "CDE"

          "F5": "FGH"

    }

}


凤凰求蛊
浏览 148回答 2
2回答

温温酱

http://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonUnwrapped.htmlpublic class A{    @JsonUnwrapped    private B b;    public User getB() ...}

蝴蝶刀刀

创建一个委托类AB:public final class AB {    private final A a;    private final B b;    public AB(A a, B b) {        this.a = a;        this.b = b;    }    // Delegation methods to A    public int    getF1() { return this.a.getF1(); }    public String getF2() { return this.a.getF2(); }    // Delegation methods to B    public int    getF3() { return this.b.getF3(); }    public String getF4() { return this.b.getF4(); }    public String getF5() { return this.b.getF5(); }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java