How to map json to object using spring boot

11,091

Solution 1

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.

@RestController
public class CustomerController {
    //@Autowired CustomerService customerService;

    @RequestMapping(path="/customers", method= RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    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 {
    @JsonProperty("customerId")
    private long OMG;
    @JsonProperty("firstName")
    private String WTF;
    @JsonProperty("lastName")
    private String LOL;
    @JsonProperty("town")
    private String YOLO;
}

Solution 2

Spring Boot does grouping dependencies, glue and default configuration. It is not a serialization api. You should use Jackson to perform your need

You shoud map your class such as :

public class Customer {

  @JsonProperty("customerId")
  private long OMG;
  @JsonProperty("firstName")
  private String WTF;
  @JsonProperty("lastName")
  private String LOL;
  @JsonProperty("town")
  private String YOLO;  
   ....
}

From JsonProperty annotation Javadoc :

Marker annotation that can be used to define a non-static method as a "setter" or "getter" for a logical property (depending on its signature), or non-static object field to be used (serialized, deserialized) as a logical property.

Default value ("") indicates that the field name is used as the property name without any modifications, but it can be specified to non-empty value to specify different name. Property name refers to name used externally, as the field name in JSON objects.

Share:
11,091
filemonczyk
Author by

filemonczyk

Updated on June 04, 2022

Comments

  • filemonczyk
    filemonczyk almost 2 years

    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??