【问题标题】:Creating JSON by combining fields from two classes通过组合来自两个类的字段来创建 JSON
【发布时间】:2019-07-14 21:16:16
【问题描述】:

我有两个班: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 ,我可以实现 这个,但我正在寻找一些基于弹簧的方法来实现这个

2.) 在 B 类中使用 @Embeddable 然后在 A 类中创建引用创建 JSON中的附加标签B如图所示:

{
   "F1": 123
   "F2": "ABC"
    b: {
          "F3": 456
          "F4": "CDE"
          "F5": "FGH"
    }
}

【问题讨论】:

  • 使用AB 的委托方法创建类AB。我的意思是你应该知道你需要一个组合对象,因为你只能从控制器方法返回一个值。这不像你可以return a, b;
  • 我不确定委托方法是什么。可以详细解释一下吗?

标签: java json spring spring-boot jackson


【解决方案1】:

使用 jackson @JsonUnwrapped 怎么样?

http://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html

public class A{

    @JsonUnwrapped
    private B b;

    public User getB() ...
}

【讨论】:

    【解决方案2】:

    创建一个委托类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(); }
    }
    

    【讨论】:

    • 这需要再创建一个类。 @JsonUnwrapped 在 spring 工作时是更好的方法
    • @ASharma7 除非A 可以包含/扩展B 或反之亦然,否则您仍然需要一个类来组合它们。我同意@JsonUnwrapped 更简单,因为您不需要创建所有委托方法。
    • 包含你的意思是 class A{ private int F1;私有字符串 F2; @JsonUnwrapped 私人 B b; } ???
    • @ASharma7 是的,比如Sanjay is doing
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2018-04-12
    • 2017-11-15
    • 2014-09-05
    • 2017-02-17
    • 2016-01-05
    • 2014-06-19
    相关资源
    最近更新 更多