Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How JSON body is converted to POJO in Spring MVC

I have a class

class Student {
    String id;
    String name;
    //getters
    //setters
}

I have a JSON Request

{
  "id": "1",
  "name": "asd",
}

I have a REST API

@RequestMapping(value = "/student", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody String getstudent(HttpServletRequest request, HttpServletResponse response,
            @RequestBody Student student,
            @RequestHeader HttpHeaders requestHeaders) {

     return null;
}

When I call this API, and visualise this student object, both the fields have values from the request I provided.

What I don't understand is:

  1. how the JSON values got directly mapped to Student class object ?
  2. is there serialization/de-serialization involved ?
  3. is there any importance of constructor in student class ?
like image 700
user1379280 Avatar asked Apr 21 '18 23:04

user1379280


People also ask

How do you convert JSON to Java object?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

How do you use POJO sample POJO code for a JSON?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.


1 Answers

1) How the JSON values got directly mapped to Student class object:

The web applications you're using configured with Spring MVC support (configured with @EnableWebMvc, @Configuration and etc.).

There are some HttpMessageConverters enabled by default.

Receiving a new request, Spring uses Accept header to determine the media type. Then it finds registered converter that can deal with the media type. it will use it to convert the entity and send back the response. Receiving a request with JSON info - Spring uses Content-Type header to determine the media type of the request body.

It will then search for a HttpMessageConverter that can convert the body sent by the client to a Java Object.

For example MappingJackson2HttpMessageConverter is a one of JSON converters:

public class MappingJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter Implementation of HttpMessageConverter that can read and write JSON using Jackson 2.x's ObjectMapper. This converter can be used to bind to typed beans, or untyped HashMap instances.

By default, this converter supports application/json and application/*+json with UTF-8 character set. This can be overridden by setting the supportedMediaTypes property.

The default constructor uses the default configuration provided by Jackson2ObjectMapperBuilder.

Compatible with Jackson 2.9 and higher, as of Spring 5.0.

@RequestBody used on the argument tells Spring that the HTTP Request should be deserialized to the Java entity. Content-Type header specified by the client application will help to determine the appropriate converter.

@ResponseBody on a method indicates to Spring that the return value is serialized directly to the body of the HTTP Response.

2) Is there serialization/de-serialization involved?

Serialization and deserialization are directly involved.

Public fields, fields with provided getters are serializable and deserializable. A setter makes a non-public field deserializable only. Global configuration can also be done at the ObjectMapper level, to use either public fields or getter/setter methods for serialization.

3) Is there any importance of constructor in student class?

Constructor is not involved by default. As I mentioned in previous section, getters and setters are used to access fields.

However constructor can be configured using @JsonCreator and @JsonProperty to participate in serialization/deserialization process:

@JsonCreator
public Student (@JsonProperty("id") String id, @JsonProperty("name") String name) {
    this.id = id;
    this.name = name;
}
like image 158
J-Alex Avatar answered Oct 12 '22 10:10

J-Alex