filemonczyk filemonczyk - 1 year ago 258
Java Question

How to map json to object using spring boot

Hello I'd like to know how I could mapp my json message to object in java when using spring boot.

Let's say I'm getting json like

"customerId": 2,
"firstName": "Jan",
"lastName": "Nowak",
"town": "Katowice"

and I'd like to make it entity in my java program:
and for whatever reason I dont want to have match on field names

public class Customer {

//Something like @Map("customerId")
private long OMG;
//Something like @Map("firstName")
private String WTF;
//Something like @Map("lastName")
private String LOL;
//Something like @Map("town")
private String YOLO;

I cannot find what annotation I should use, Not using jackson, just built in spring boot converter??

Answer Source

Spring boot comes with Jackson out-of-the-box.

You can use @RequestBody Spring MVC annotation to un-marshall json string to Java object... something like this.

public class CustomerController {
    //@Autowired CustomerService customerService;

    @RequestMapping(path="/customers", method= RequestMethod.POST)
    public Customer postCustomer(@RequestBody Customer customer){
        //return customerService.createCustomer(customer);

Annotate your entities member elements with @JsonProperty with corresponding json field names.

public class Customer {
    private long OMG;
    private String WTF;
    private String LOL;
    private String YOLO;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download