0

I need to read data from database and send it to some MQ in JSON format. I am using java 8,spring boot. My current process --

Read Data from DB --- > Map to POJO --- >Convert to JSON using object mapper (Jackson )

Problem with above is my Pojo classes need to be changed if JSON structure changes.

How can I avoid it? Below is the JSON schema that I have. Suppose if some field gets added to this schema. How can I avoid the code change? Can I make it dynamic? Eg. lets say some fields get added to fname,lname or address. How can I avoid the code change?

{
    "name":   {
                "fname" :  {
                             "displayName":"FirstName",
                             "dataType":"String"
                           }
                "lname"  : {
                             "displayName":"LastName",
                             "dataType":"String"
                           }
               },
    "address": {
                   "displayName":"Address",
                   "dataType":"String"
               }
  }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Pale Blue Dot
  • 511
  • 2
  • 13
  • 33

1 Answers1

0
  • Add GSON Dependency
  • To make it prettyPrinting use GsonBuilder()-> GsonBuilder().setPrettyPrinting().create();
  • toJson(Object)

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>
    
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    Person person = newPerson();
    String jsonString = gson.toJson(person);
    System.out.println(jsonString);
    
    
    private static Person newPerson() {
     List<String> hobbies = Arrays.asList("Cricket", "Guitar", "Coin Collection");
     Map<String, String> languages = new HashMap<>();
     languages.put("French", "Beginner");
     languages.put("German", "Intermediate");
     languages.put("Spanish", "Advanced");
     Person person = new Person("Max", 22, hobbies, languages);
     return person;
    }
    
kkrkuldeep
  • 83
  • 5