M
M
melouw2016-04-27 22:04:22
Java
melouw, 2016-04-27 22:04:22

Is it right to create many POJO classes to generate json response?

Hello.
Requests for data are coming from the client, and they must be returned as Json.
json example:

{
  "root" : {
    "name1" : {
      "name1_1" : {
        "field1" : 10,
        "field2" : 20
      },
      "name1_2" : {
        "field1" : 30,
        "field2" : 40
      }
    },
    "name2" : {
      "name2_1" : {
        "obj1" : {
          "field3" : 50.01,
          "field4" : 60.02,
          "field5" : 70.03
        },
        "obj2" : {
          "field3" : 80.80,
          "field4" : 90.90,
          "field5" : 100.90
        },
        "obj3" : {
          "field3" : 110,
          "field4" : 120,
          "field5" : 130
        }
      }
    }
  }
}

The first thing that came to my mind was to create many different classes and jackson would simply return them, but the data is quite heterogeneous and the number of classes has grown rapidly, this confused me a lot, since there are about 20 classes in the package that essentially have nothing: two fields , constructor and get/setters.
So the question is, are my thoughts correct? And is there a good practice for solving such problems?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
guras256, 2016-04-28
@guras256

Yes, it is normal. Your application has an api that contains the entities you work with and return to the client (and the internal representation and external model may differ).
To get rid of the boilerplate with getters, setters and more, use lombok

/**
 * аннотация @Data добавит в байткод методы 
 * getString, setString, 
 * getAnotherString, setAnotherString, 
 * equals, hashcode, toString
 */
@Data
public class App {
    private String string;
    private String anotherString;
}

There are a lot of handy annotations in this library. You can install lombok plugin for support in idea environment

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question