Home » Java » java – Long json request from pojo class having too many fields-Exceptionshub

java – Long json request from pojo class having too many fields-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to know how to create a long JSON request from POJO classes and maintain code quality?
I have around 34 classes and I have to create a JSON request using it. My class having around 30 private fields with getters and setters.

I used ObjectMapper to create JSON, but I want to know how to maintain the setter of different classes?

Example

class A{               
 private int a1;
 private int a2;
 private int an;    
 private B b;
}

class B{   
 private int b1;
 private int b2;
 private int bn;    
 private C c;
}    

I did code like below for above class

    A a =new A();
    a.setA1();
    a.setA2();
    a.setA3();
    A.setAn();

    B b=new B();
    b.setB1();
    b.setB2();
    b.setB3();
    b.setBn();
    A.setB(b);

    ObjectMapper Obj = new ObjectMapper();
    String jsonStr = Obj.writeValueAsString(request);
    System.out.println(jsonStr);

Is it correct wary or how can I remove the setter part from the main code and manage another location?

How to&Answers:

You can create a top level class and add all the 34 classes as properties to your top level class and getters and setters for those properties and annotate those properties with jackson @JsonProperty(“value”)

Example:-

public class TopLevel{

@JsonProperty("A")
private A a;
@JsonProperty("B")
private B b;
@JsonProperty("C")
private C c;
..
..
..
..
..
your 34 classes and 
//constructor with all the parameters.... 

And call the Topleve class in your object mapper as

ObjectMapper mapper = new ObjectMapper();
     A a = new A(a1,a2,an);
     B b = new B(b1,b2,bn);
     ..
     .. so on..
     TopLevel top= new TopLevel(a, b, c,........so on);
     String jsonWriter = mapper.writerWithDefaultPrettyPrinter()
         .writeValueAsString(top);
     System.out.println(jsonWriter);