You are trying to manually do something that Spring MVC is already automatically for you. Spring automatically displays a representation of the return type and performs the conversion. How can you find out from http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc . In your case, its conversion to JSON.
It works when I return a String or ArrayList
What happens under the hood is that Spring MVC uses the Jackson library to convert the return type to JSON. And since it has no problems with converting to String or List, everything works fine.
What happens in the code you posted is that the Jackson manipulator object is trying to convert the JSONObject instance to JSON, and this fails because Jackson expects a POJO that is not an instance of JSONObject.
For it to work, you just have to write POJO and return it. So something like
public class Person { private String name; private Integer age; private Boolean married; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Boolean getMarried() { return married; } public void setMarried(Boolean married) { this.married = married; } }
and change your method to
@RequestMapping("/test") @ResponseBody public Person test() { Person person = new Person(); person.setName("Dade"); person.setAge(23); person.setMarried(false); return person; }
As for your mistake, you will see the same exception in the working example, if, for example, you delete getters and setters or call them wrong, the exception occurs when you try to convert to a view and you get 406 error
source share