Home > Blockchain >  Best practice to create POJO / DTO for sending deep nested JSON
Best practice to create POJO / DTO for sending deep nested JSON

Time:09-08

When developing our API in spring boot that interacts with a third party API, I have to create a DTO to populate and send to a third party. Thing is, the required JSON has a ton of nested objects. For example:

{
  "profile": {
    "firstName": "firstname",
    "credentials": {
        "password" : {
          "hook": {
            "type": "default"
          }
        }
    }
  }
}

So, what is simple to express in a JSON object is not simple to express in POJO/DTO classes, due to the high number of nested objects.

Should I create public or anonymous classes for all the nested properties? Or is there a better way to do this?

For example using anonymous, I can keep everything in one java file by not making the subobjects public. What are your techniques for this?

CodePudding user response:

known problem... what I used often:

  • wrap (hide) third party api in a module
  • create custom pojo(s) containing only values needed from your domain logic
  • use only this pojo(s) to interact between your domain/third party module
  • create module private/inner classes mapping the third party api model as pojos
  • or consider using nested maps instead with custom jackson de/serializers
  • map domain pojo to api pojos

or, a bit hacky, if you only need to change same values

  • store json request payload as a template with placeholders
  • use e.g. regex to replace before send

CodePudding user response:

You can do what you suggested or simply de-serialize it into Map<String, Object> Using map makes it easy but you won't have content validation and modifying the content (if you need it becomes complex)

  • Related