3

I'm new to springs and I wondering if I can return the contents of a Java Bean as a JSON response. Basically, I would have a class XYZ,

public class XYZ {
    private String name,
    private String email,
    //Setters and getters...
} 

I was wondering if I can get a response which has

{name: 'Something', email: 'something@somethingelse.com'}

without any manual processing. Thanks in advance!

Abilash
  • 6,089
  • 6
  • 25
  • 30

3 Answers3

4

Spring @ResponseBody is used to return json automatically.

@ResponseBody    
public XYZ response() {
    XYZ xyz = new XYZ();
    xyz.setName("name");
    xyz.setEmail("email@com");
    return xyz
}

You should add jackson to webapp runtime classpath.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Larry.Z
  • 3,694
  • 1
  • 20
  • 17
  • NB you have to have at least one field+getter/setter or you'll get " No converter found for return value of type: class ..." – rogerdpack Apr 16 '19 at 17:28
3

We use fastjson to JSONize java beans. It's fast and convenient.

public @ResponseBody
String showLesson() {
    Map<String, Object> map = new HashMap<String, Object>();
    return JSON.toJSONString(map);
}
strongwillow
  • 328
  • 2
  • 13
2

There are plenty of libraries out there for json conversion. You can use Jackson which is supported by Spring MVC.

XYZ obj = /*instance*/;
ObjectMapper converter = new ObjectMapper();
System.out.println(converter.writeValueAsString(obj));
rocketboy
  • 9,573
  • 2
  • 34
  • 36