SpringUser
SpringUser

Reputation: 45

How to add objects to JSON

In post service, I am using below method to parse and update Database:

ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(<String>);
        UserLogin userLogin = mapper.convertValue(node.get("UserLogin"), UserLogin.class);
        UserSecurityDetails userSecurityDetails = mapper.convertValue(node.get("UserSecurityDetails"), UserSecurity

Now, In get service, I want to send the same data by retieving from DB and adding to JSON. Could anyone suggest what is the best way?

Sample JSON to be formed:

{

"UserLogin":
    {
        "user_login_id": "10011",
        "user_password": "password"
    },
"UserSecurityDetails":
    {
        "user_sequence_id": "1",
        "seq_question_id": "1",
        "seq_answer": "Test Answer"
    }

}

Upvotes: 0

Views: 121

Answers (1)

Dilip Kumar
Dilip Kumar

Reputation: 2534

Create a Wrapper POJO having UserLogin and UserSecurityDetails. Jackson will automatically deserialize to your object.

It will be good practice to expect required Object instead of creating objects from String.

Your Wrapper class will be like

public class SecurityDetailsWrapper {
     private UserLogin;
     private UserSecurityDetails;

     // costructor

     // getters and setters
}

in your Controller's method you can expect SecurityDetailsWrapper.

like

public void someFunction(@RequestBody SecurityDetailsWrapper wrapper) {
  // business logic
}

Jackson will takes care of Deserialization.

Upvotes: 1

Related Questions