需求:请求数据格式为json类型,并将其输出
1.工具类
public class WebResult implements Serializable {
private static final long serialVersionUID = 1L;
private int success;
private String errorMessage = "";
private Map<String, Object> result = new HashMap<>();
public void put(String key, Object value) {
result.put(key, value);
}
public void remove(String key) {
result.remove(key);
}
//get和set方法
}
public class WebResultHelper {
private WebResultHelper(){}
public static WebResult newResult(){
WebResult result = new WebResult();
result.setSuccess(1);
return result;
}
public static WebResult newErrorResult(String errMessage){
WebResult result = new WebResult();
result.setSuccess(0);
result.setErrorMessage(errMessage);
return result;
}
}
2.controller层开发
//提交json数据并展示
@RequestMapping(value = "/json",method = RequestMethod.POST)
@ResponseBody
public WebResult json(@RequestBody Item item){
WebResult webResult = WebResultHelper.newResult();
try {
webResult.setSuccess(1);
webResult.put("data",item);
}catch (Exception e){
return WebResultHelper.newErrorResult("json串解析错误");
}
return webResult;
}
3.测试