Spring获取Object映射定制方法的请求

时间:2015-11-23 08:42:22

标签: java json spring spring-mvc httprequest

我想知道如何将Spring Controller GET请求映射到我的对象。

我遇到一种情况,我为单个搜索API启用了GET和POST请求。

我收到的POST api为JSON数据类型,使用

  

CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES

将json转换为我的对象的策略。

将在我的Java模式中将字段date_to转换为dateTo。

但是如果我通过GET收到相同的请求,我需要传递dateTo而不是date_to。这给最终用户带来了很多困惑。

我正在寻找类似下面的内容

class MySearchRequestDTO{
    private int start = 0;
    private int count = 10;

    @RequestAttribute(name="date_from")
    private Date dateFrom;

    @RequestAttribute(name="date_to")
    private Date dateTo;

    //Getters and Setters
}

控制器类

@RequestMapping(value = "/search", method = {RequestMethod.GET})
public ApiSuccessResponse aSearchGet(MySearchRequestDTO request) throws IMSException{
    return new ApiSuccessResponse(inventoryService.aSearch(request));
}

@RequestMapping(value = "/search", method = {RequestMethod.POST})
public ApiSuccessResponse aSearchPost(@RequestBody MySearchRequestDTO request) throws IMSException{
    return new ApiSuccessResponse(inventoryService.aSearch(request));
}

在这种情况下,在我的应用程序网址类型中遵循相同名称策略的最佳方法是什么。如果有人以更好的方式解决了这个问题,请告诉我。

非常感谢您阅读本文的时间。

2 个答案:

答案 0 :(得分:0)

Spring使用Jackson映射器将json映射到对象,反之亦然。使用Jackson您可以为具体类实现自己的映射器版本,因此只需为您需要的类编写自己的序列化器和反序列化器实现。

答案 1 :(得分:0)

由于春天使用jackson,以下方法有效。

public class MySearchRequestDTO {
    int test;

    @JsonProperty("t")
    public int getTest() {
      return test;
    }

    @JsonProperty("t")
    public void setTest(int test) {
      this.test = test;
    }
}

然后:

MySearchRequestDTO c = new MySearchRequestDTO();
c.setTest(5);

ObjectMapper mapper = new ObjectMapper();
System.out.println("Serialization: " + mapper.writeValueAsString(c));

MySearchRequestDTO r = mapper.readValue("{\"t\":25}",MySearchRequestDTO.class);
System.out.println("Deserialization: " + r.getTest());

结果:

Serialization: {"t":5}
Deserialization: 25