Spring MVC返回JSONS和异常处理 [英] Spring MVC returning JSONS and exception Handling

查看:161
本文介绍了Spring MVC返回JSONS和异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



要进一步阐述,我有一个名为UserDetails的对象,它有两个字段,名为name,emailAddress

  @ResponseBody UserDetails 

现在,json返回的样子看起来像


{name:TheUsersName,
emailAddress:abc@abc123.com}


有什么办法可以在返回之前修改json(所有控制器中的所有方法中的所有jsons),其中将添加status字段,其他json数据将在data json中的关键。



另外,当某个地方的java服务器引发异常时,如何将json返回到前端,json应该具有status:false和异常名称(至少是状态

解决方案

是的。返回一个模型和一个视图。

  public ModelMap getUserDetails(){
UserDetails userDetails; //从某个地方获取此对象
ModelMap map = new ModelMap()(;
map.addAttribute(data,userDetails);
map.addAttribute(success,true);
返回地图;
}

添加你会做的例外与key相同的方式,成功= false。


I am using Spring MVC with Controllers, my question is how do I return a JSON response which is different from the @ResponseBody object which is returned and convereted to a JSON to be returned.

To elaborate further, I have the object called "UserDetails" which has two fields called "name", "emailAddress"

@ResponseBody UserDetails

now the json returned will look like

{ name : "TheUsersName", emailAddress:"abc@abc123.com" }

Is there any way I can modify the json before returning (ALL jsons in all methods across all controllers) where a "status" field will be added and the other json data will be under the "data" key in the json.

Also how do I return a json to the frontend when the java server from somewhere throws an exception, the json should have "status : false" and the exception name (atleast the status part though)

解决方案

Yes. Return a model and a view instead.

public ModelMap getUserDetails() {
    UserDetails userDetails; // get this object from somewhere
    ModelMap map = new ModelMap()(;
    map.addAttribute("data", userDetails);
    map.addAttribute("success", true);
    return map;
}

To add the exception you'd do it the same way with a key and success = false.

这篇关于Spring MVC返回JSONS和异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆