Converting a Java class with nested array of Java classes to JSON

168 views Asked by At

Is there a convenient way to convert a Java class with a nested array of Java classes into JSON? For instance I want to convert an instance f the following class to JSON:

public class Students {
  private final String serial_no;
  private final class InnerData {
     private final String[] strs;
     private final String name;
     private final String city;
  }
  private final StudentList[] students;

}

as

{ 
  "serial_no" : null,
  students : [
    {
       "strs" : ["athlete", "grammarian"],
       "name" : "John Smith",
       "city" : "Auckland"
    },
    {
       "strs" : ["postmaster", "swimmer"],
       "name" : "Jane Doe",
       "city" : "Sydney"
    }
  ]
}

What is the best way to do this in Spring? The examples I have come across seem to be simple classes so far with no nesting.

1

There are 1 answers

0
Mudassar On

To return an java object in JSON form from an spring objects requires two simple configurations: 1) Adding 'jackson-mapper-asl' dependency to the classpath 2) Add @ResponseBody annotation to the controller's method 

1) Adding 'jackson-mapper-asl' dependency to the classpath

In a spring mvc project we need to add a 'jackson-mapper-asl' dependency to the pom.xml file, and object to json conversion is done by default.

<dependency>   <groupId>org.codehaus.jackson</groupId>   <artifactId>jackson-mapper-asl</artifactId>   <version>1.9.10</version>  </dependency>  

2) Add @ResponseBody annotation to the controller's method

Second thing we need to do is to use '@ResponseBody' annotation against the controller's method. This will make spring understand that method return value should be bound to the web response body.

@RequestMapping("studentlist")   public 

@ResponseBody   List<Student> getStudentList() {    List<Student> studentList = new ArrayList<Student>();    studentList.add(new Student(23, "Meghna", "Naidu", "[email protected]",      "8978767878"));    studentList.add(new Student(3, "Robert", "Parera", "[email protected]",      "8978767878"));    studentList.add(new Student(93, "Andrew", "Strauss",      "[email protected]", "8978767878"));    studentList.add(new Student(239, "Eddy", "Knight", "[email protected]",      "7978767878"));      return studentList;   
    }