javajsonspring-bootjacksondomain-object

How to receive customized JSON Object in Spring boot Api post Method


I am trying to receive a JSON object in @RequestBody which is not known to me i.e. the JSON Object could be of any length and data.

Let's say, JSON could be as shown below

{'seqNo': 10 }

{'country': 'US', 'state': 'CA'}

{'customer': 'Alex', product: 'UPS', date:'25-Mar-2018'}

And In Spring Boot Api, I have a method to receive that JSON Object.

@PostMapping(value = "/lookup")
public ResponseEntity<AppResponse> getLookup(@RequestBody LookupRequestObject lookupRequestObject) {

        // THIS METHOD KNOWS WHICH FIELD TO USE
        // FURTHER LOGIC WOULD BE HERE.


        return ResponseEntity.ok(response);

    }

I have read about Jackson Serialization but still finding solution for this.

Customize the Jackson ObjectMapper

Any help would be much appreciated.


Solution

  • You could just use a map for your input. Then you can access filed in the map depending on what kind of fields it contains.

    @PostMapping(value = "/lookup")
    public ResponseEntity<AppResponse> getLookup(@RequestBody Map<String, Object> lookupRequestObject) {
    
        // THIS METHOD KNOWS WHICH FIELD TO USE
        // FURTHER LOGIC WOULD BE HERE.
    
        return ResponseEntity.ok(response);
    }