JQ Ajax应该选择Json还是Json字符串向后端传递比较合适?

比如说,现在需求是希望把前端的数据传向SpringMVC,绑定在请求方法的一个实体参数中

@Request(value="test", method=RequestMethod.POST) @ResponseBody
public String test(TwoDate td) {
    return td.toString();
}

其中,TwoDate是那个实体类,有两个被@DateTimeFormat所标记的Date类型的私有域。

1、我尝试了一下以下的方式

$.ajax({
    type:"post",
    url:"/test",
    data:saveData,
    success:function(data) {
        alert(data);
    },
    error:function(data) {
        alert('error');
    }
});

没有问题,前端的saveData成功绑定到了TwoDate td中。

2、随后,我换了以下的方式

    $.ajax({
        type:"post",
        url:"/test",
        dataType:"json",
        contentType : 'application/json',
        data:JSON.stringify(saveData),
        success:function(data) {
            alert(data);
        },
        error:function(data) {
            alert('error');
        }
    });

并在请求方法的参数前面追加了个@RequestBody 注解,
报了HTTP-400错误,控制台提示我

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpMessageNotReadable
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.util.Date from String "2017-01-01 02:03:04": not a valid representation (error: Failed to parse Date value '2017-01-01 02:03:04': Can not parse date "2017-01-01 02:03:04Z": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null))

非常奇怪,而当我把实体类的两个域的类型从Date改成String后,又正常了

3、我的dispatcherservlet.xml的配置关于消息转换的配置是这样的

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class = "org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            </bean>
            <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

所以我想问一下,实际开发中,向后端传递JSON字符串是否更合适?
JSON字符串有办法绑定到含有Date类型的实体中吗?
如果没有办法,那么大家的做法是否是将这些Date类型换成String类型吗?

不胜感激:)

哆啦的时光机
浏览 1493回答 2
2回答

千巷猫影

用注解JsonFormat也可以实现,还自带时区修改
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java