In a Spring MVC project, we can directly return a JSON object. This feature is very useful when combined with ajax request from the client side. Here is few simple step to do this:
- Import JSON dependencies (jackson library) to your project
- Create Java objects, which will be converted to JSON object
- Create a simple Spring Controller to handle the request
- Test it using jetty server.
You can also download the source code here: https://github.com/nxhoaf/spring-mvc-json. Here, I assume that you are already familiar with Maven. If it’s not the case, you can certainly manually insert dependencies in your classpath.
1. JSON dependencies to your pom.xml
<!-- Enable JSON via Jackson --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.10</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.10</version> </dependency>
2. Java Object, which will be converted to JSON
// --------------- Person.java ------------------ package com.gmail.nxhoaf; public class Person { private String name; private int age; public Person() {} public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } // --------------- Shop.java ------------------ package com.gmail.nxhoaf; import java.util.ArrayList; import java.util.List; public class Shop { private String name; private List<Person> staffs; public Shop() { staffs = new ArrayList<Person>(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Person> getStaffs() { return staffs; } public void setStaffs(List<Person> staffs) { this.staffs = staffs; } public void addStaff(Person staff) { staffs.add(staff); } }
3. Create simple Spring Controller
package com.gmail.nxhoaf; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/json") public class JSonController { @RequestMapping(method = RequestMethod.GET) public @ResponseBody Shop getShopInJSON() { Shop shop = new Shop(); shop.setName("myShop"); Person p1 = new Person("Alice", 20); Person p2 = new Person("Bob", 30); shop.addStaff(p1); shop.addStaff(p2); return shop; } }
That is! Now, we test it with our jetty server. You might want to see here Spring MVC: Creating a Project from Scratch using Maven to see how to run a Spring MVC project with jetty
mvn clean install mvn jetty:run
Then, open http://localhost:8080/spring-mvc-json/json, you should see the following result: