Thomas Betous Thomas Betous - 1 month ago 7
JSON Question

Jackson FasterXML : How does Spring know how to json object?

I am currently following this tutorial about Spring MVC and REST service. It is a simple hello world project.

There is something I don't understand. In the pom.xml we set jackson dependency but it is never configurated. How does Spring know how to json object ?

Here is samples of code :

pom xml (dependencies) :

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.library}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.library}</version>
</dependency>
</dependencies>


AppConfiguration :

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "package.to.scan")
public class AppConfiguration {
}


AppInitializer :

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfiguration.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}


AppController :

@RestController
public class AppController {

@RequestMapping("/")
public String welcome() {
return "Welcome to RestTemplate Example.";
}

@RequestMapping("/hello/{player}")
public Message message(@PathVariable String player) {

Message msg = new Message(player, "Hello " + player);
return msg;
}
}


Model :

public class Message {

String name;
String text;

public Message(){

}

public Message(String name, String text) {
this.name = name;
this.text = text;
}

public String getName() {
return name;
}

public String getText() {
return text;
}

}

Answer

Spring has a default set of HttpMessageConverters, one of them being MappingJackson2HttpMessageConverter, which is used if the content type is json and if Jackson is available in the classpath.

Comments