2

I have two classes : class A , class B

class A{
 private int F1;
 private String F2;
}

class B{
 private int F3;
 private String F4;
 private String F5;
}

I want a JSON like this:

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

I am using springboot which creates JSON as soon as I return object from @RestController. How can I achieve the above json using these two classes.

Note : 1.) I already know that by using class A extends B , I can achieve this but I am looking for some spring based method to achieve this

2.) Using @Embeddable in class B & then creating reference in Class A creates additional tag B in JSON as shown :

{
   "F1": 123
   "F2": "ABC"
    b: {
          "F3": 456
          "F4": "CDE"
          "F5": "FGH"
    }
}
ASharma7
  • 726
  • 3
  • 8
  • 27
  • 1
    Create class `AB` with delegation methods to `A` and `B`. I mean you kinda should know that you need a combo object, since you can only return one value from the controller method. It's not like you can `return a, b;` – Andreas Feb 21 '19 at 03:46
  • I am not sure what delegation methods is . May you please explain in more detail ? – ASharma7 Feb 21 '19 at 03:48
  • See [What is the purpose of a delegation pattern?](https://stackoverflow.com/q/7168714/5221149) – Andreas Feb 21 '19 at 03:54

2 Answers2

5

How about using 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() ...
}
Sanjay
  • 2,481
  • 1
  • 13
  • 28
1

Create a delegating class 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(); }
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • This needs one more class to be created. @JsonUnwrapped is much better approach while working on spring – ASharma7 Feb 21 '19 at 04:36
  • @ASharma7 Unless `A` can include/extend `B` or vice-versa, you still need one more class to combine them. I do agree that `@JsonUnwrapped` is simpler, since you won't need to create all the delegation methods. – Andreas Feb 21 '19 at 16:24
  • By including you mean class A{ private int F1; private String F2; @JsonUnwrapped private B b; } ??? – ASharma7 Feb 21 '19 at 16:33
  • @ASharma7 Yes, like [Sanjay is doing](https://stackoverflow.com/a/54798974/5221149). – Andreas Feb 21 '19 at 16:56