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