0

I have a spring boot API . The call is as below:

@PostMapping("/call-back")
    public BaseResponse<String> callBack(@RequestBody CallBackDTO callbackRequest) {
}

the CallBackDTO object is as below:

public class CallBackDTO {
    private String msgRefNo;
    private Object Message;
}

when I pass in this json request, its like below:

{
    "msgRefNo": "202502070000000137"
    "Message": {
        //unknown, random stuff.
    }
}
  1. I am able to receive msgRefNo. But I cant detect Message.How do i save the Message field, with undefined format ?
3
  • 2
    Have you tried using Map<String, Object>? Commented Nov 4 at 3:24
  • 2
    You can use the JsonNode to represent a JSON object for your Message field. Commented Nov 4 at 3:47
  • Although I did not try, but if structure is nested and you are using Map<String, Object> then same problem will arise again. you can make use of jackson(comes builtin with mvc) or gson(google's library). These 2 libraries help java devs to read data from Json, when type is thing that you are not sure about. Commented Nov 4 at 15:59

2 Answers 2

1

Read about jackson/gson libraries in spring boot, they will be helpful in this case. Replace Object Message with JsonNode (from Jackson).

public class CallBackDTO {
    private String msgRefNo;
    private JsonNode Message;  // <<<<<<<<
    
    // getters and setters
}

Now you can access the unknown fields.

@PostMapping("/call-back") 
public BaseResponse<String> callBack(@RequestBody CallBackDTO callbackRequest) { 
    var data = callbackRequest.getMessage().get("random"); 
}

do exception handling too if field random isn't present in the message.

Sign up to request clarification or add additional context in comments.

Comments

0

To add to @Gil's answer, You can use Map<String, Object> in your CallBackDTO as following:

public class CallBackDTO {  
    private String msgRefNo;  
    private Map<String, Object> message;  

    // setter / getter  
}  

now your JSON will deserialized to a Map like this:

{     
    "msgRefNo": "20250411070605",     
    "Message": {       
        "keyA": "test",       
        "keyB": 123  
    }   
}

with this approach you could easily invoke each message separately by its key, as follow:

request.getMessage.get("keyA"):   
-\> test  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.