1

我正在使用 Spring 设置,使用 json 映射转换器将 POJO 类作为 json 发送回客户端。

例如:

@RequestMapping
@ResponseBody
public User getUser() {
    User user = getUser();
    return user;
}

这将向客户返回例如类似的东西:

{ 'username': 'My username', 'lastname': 'My lastname' }

我想拦截我所有的控制器操作以将 json 包装成如下内容:

{
  'status': 200,
  'data': { 'username': 'My username', 'lastname': 'My lastname' }
}

最好的方法是什么?

4

3 回答 3

0

我通过扩展为您的问题找到了可能的解决方案MappingJackson2HttpMessageConverter

public class MyMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        //outputMessage.getHeaders().add("code", DigestUtils.md5Hex(object.toString()));
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", 200);
        map.put("data", object);
        super.writeInternal(map, outputMessage);    //To change body of overridden methods use File | Settings | File Templates.
    }
}

然后将你自己的 conventer bean 添加到 spring-mvc 配置文件中

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="com.xxx.utils.MyMappingJackson2HttpMessageConverter">
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
<mvc:default-servlet-handler/>

此方法适用于每个@ResponseBody处理程序方法。

请注意,它会更改默认的 Spring 动作,您应该考虑一下。

于 2013-08-17T18:30:40.710 回答
0
You can also do something like this

<mvc:annotation-driven>  <!-- this is added for validations to work -->
    <mvc:message-converters register-defaults="true">
        <ref bean="jsonMessageConverter"/>
    </mvc:message-converters>
    </mvc:annotation-driven>

<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
         <property name="objectMapper" ref="YourDtoWrapper"/> 
</bean>

<bean id="YourDtoWrapper" class="com.YourDtoWrapper"/>

inside your YourDtoWrapper class you can do something like this


public void writeValue(JsonGenerator jgen, Object value) throws IOException, JsonGenerationException, JsonMappingException {

        SomeDTO<Object> someDto = new SomeDTO<Object>("SUCCESS");//you can use an enum here
        someDto.setDto(value);//here dto is a property of someDTO

        super.writeValue(jgen, SomeDTO.getAsMap(someDto));
    }

this will give u result some thing like this

{
serviceResult: "SUCCESS"
context: null
dto: {
id: 1
firstName: "test"
lastName: "admin"
email: "admin@test.com"
phone: 1234
userName: "admin"
password: null
createdBy: "admin"
createdDate: null
statusId: 1
statusName: "ACTIVE"
organisationId: 1
organisationName: "test"
userTypeId: 1
userTypeName: "ADMIN"
roleIds: [0]
}
}
于 2014-03-21T14:02:11.123 回答
0

简单地说,您可以像这样创建地图

@RequestMapping(value = "/user")
@ResponseBody
public Map<String, Object> getUser(){
    User user = new User();
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("status", 200);
    map.put("data", user);
    return map;
}

对于常见用法,您可以创建一个 POJO

    public static class ResutInfo{
    private int status;
    private Object data;

   //get set}

然后编写控制器方法

@RequestMapping(value = "/user")
@ResponseBody
public ResutInfo getUser2(){
    User user = new User();
    ResutInfo resutInfo = new ResutInfo();
    resutInfo.setStatus(200);
    resutInfo.setData(user);
    return resutInfo;
}
于 2013-08-14T08:03:06.453 回答