一、方法一:
使用jackson-databind直接返回对象。
二、方法二
使用Gson将对象转换成String再返回,要设置contentType为application/json。
三、方法三
将对象转换成json,然后直接写入到HttpServletResponse中。
例子如下:Controller
@Controller
public class GreetController {
private static final String template ="Hello, %s" ;
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
@ResponseBody
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World")String name ) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
@RequestMapping("/greeting1")
public void greeting1(@RequestParam(value = "name",defaultValue = "world")String name, HttpServletResponse resp){
Greeting greeting = new Greeting(counter.incrementAndGet(),String.format(template,name ));
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
try {
PrintWriter writer = resp.getWriter() ;
writer.print(JsonUtil.toJson(greeting));
}catch (IOException e){
e.printStackTrace();
}
}
@RequestMapping(value = "/greeting2",method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String greeting2(@RequestParam(value = "name",defaultValue = "lisj")String name){
Greeting greeting = new Greeting(counter.incrementAndGet(),String.format(template,name));
return JsonUtil.toJson(greeting);
}
}
JsonUtil如下:
public class JsonUtil {
private static Gson gson = new Gson();
public static String toJson(Object src){
if (src== null){
return gson.toJson(JsonNull.INSTANCE);
}
return gson.toJson(src);
}
}