java Spring MVC 返回 JSONS 和异常处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5395222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:55:14  来源:igfitidea点击:

Spring MVC returning JSONS and exception Handling

javajsonspringspring-mvcexception-handling

提问by MilindaD

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.

我正在使用带有控制器的 Spring MVC,我的问题是如何返回一个 JSON 响应,该响应与返回并转换为要返回的 JSON 的 @ResponseBody 对象不同。

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

为了进一步详细说明,我有一个名为“UserDetails”的对象,它有两个名为“name”、“emailAddress”的字段

@ResponseBody UserDetails

now the json returned will look like

现在返回的 json 看起来像

{ name : "TheUsersName", emailAddress:"[email protected]" }

{名称:“TheUsersName”,电子邮件地址:“[email protected]”}

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.

有什么方法可以在返回之前修改 json(所有控制器的所有方法中的所有 json),其中将添加“状态”字段,而其他 json 数据将位于 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)

另外,当某个地方的 java 服务器抛出异常时,我如何将 json 返回到前端,json 应该具有“状态:假”和异常名称(尽管至少是状态部分)

采纳答案by Robby Pond

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.

要添加例外,您可以使用密钥和成功 = false 以相同的方式进行操作。

回答by sourcedelica

Create a response class:

创建响应类:

public class Response<T> {
    T data;
    boolean status = true;

    public Response(T d) { data = d; }
}

Then return that from your controllers:

然后从您的控制器返回:

@ResponseBody public Response getUserDetails) {
    //...
    return new Response(userDetails);
}

For the exception you'll want to return an object like:

对于例外情况,您需要返回一个对象,如:

public class BadStatus {
    String errorMessage;
    boolean status = false;

    public BadStatus(String msg) { errorMessage = msg; }
}

@ExceptionHandler(Exception.class)
public BadStatus handleException(Exception ex, HttpServletRequest request) {
  return new BadStatus(ex.getMessage());
}

回答by Pablo Abreu

An alternate solution (works with spring 3.1), which is less invasive

替代解决方案(适用于 spring 3.1),侵入性较小

in your spring config :

在您的弹簧配置中:

<bean id="HymansonConverter"     class="org.springframework.http.converter.json.MappingHymansonHttpMessageConverter" />
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="mypackage.MyMessageConverter"
            p:delegate-ref="HymansonConverter">
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

The idea is to provide your own HttpMessageConverter that delegates to the provided Hymanson converter.

这个想法是提供您自己的 HttpMessageConverter ,它委托给提供的 Hymanson 转换器。

public class MyMessageConverter implements HttpMessageConverter<Object> {
// setters and delegating overrides ommitted for brevity
@Override
    public void write(Object t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException,
            HttpMessageNotWritableException {
// t is whatever your @ResponseBody annotated methods return
        MyPojoWrapper response = new MyPojoWrapper(t);

        delegate.write(response, contentType, outputMessage);
    }
}

This way all your pojos are wrapped with some other json that you provide there.

这样,您所有的 pojo 都与您在那里提供的其他一些 json 文件一起包装。

For exceptions, the solution proposed by ericacm is the simplest way to go (remember to annotate the 'BadStatus' return type with @ResponseBody).

对于例外情况,ericacm 提出的解决方案是最简单的方法(记得用@ResponseBody 注释'BadStatus' 返回类型)。

A caveat : your json-serialized BadStatus goes through MyMessageConverter too, so you will want to test for the object type in the overriden 'write' method, or have MyPojoWrapper handle that.

一个警告:您的 json 序列化 BadStatus 也通过 MyMessageConverter,因此您需要在重写的“write”方法中测试对象类型,或者让 MyPojoWrapper 处理它。