紧急!!求大神帮忙!Spring MVC使用@RequestBody 接收带空格的字符串,报错。 5C

实体类:
public class TestVO {
private String CreateDate;

public String getCreateDate() {
    return CreateDate;
}

public void setCreateDate(String createDate) {
    CreateDate = createDate;
}
}

Controller:

@RequestMapping(value="/test2/", headers="Accept=application/json")
@ResponseBody
public TestVO test2(@RequestBody TestVO user) {

    return user;
}


使用CURL发送请求:
curl -H "Content-Type: application/json"  -d {\"createDate\":\"2015-07-31 00:00:00\"} --request POST http://localhost:8081/HQ520/test2/
报的错误:
八月 05, 2015 1:46:35 下午 org.apache.catalina.core.StandardWrapperValve invoke

严重: Servlet.service() for servlet [rest] in context with path [/HQ520] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unexpected end-of-input in VALUE_STRING
at [Source: org.apache.catalina.connector.CoyoteInputStream@2e330425; line: 1, column: 91]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected end-of-input in VALUE_STRING
at [Source: org.apache.catalina.connector.CoyoteInputStream@2e330425; line: 1, column: 91]] with root cause
com.fasterxml.jackson.core.JsonParseException: Unexpected end-of-input in VALUE_STRING

我测试过了,应该是空格的问题,以下是我的单元测试

@Test
public void testInsertObject() throws Exception {

String url = URI + "/object";

TestVO anObject = new TestVO();
anObject.setCreateDate("2015-07-31 00:00:00");

Gson gson = new Gson();
String json = gson.toJson(anObject);

    MvcResult result = this.mockMvc.perform(MockMvcRequestBuilders.post(url).contentType(MediaType.APPLICATION_JSON)
        .content(json))
        .andDo(print())
        .andReturn();

}

这样会报错,如果改成nObject.setCreateDate("2015-07-31-00:00:00"); 就不会报错了

我认为应该是MappingJacksonHttpMessageConverter解析JSON字符串的时候,如果遇到空格就认为这个字符串结束,所以出现这个问题。

有哪位大神遇到过类似的问题?怎么解决?请指教。谢谢!

1个回答

把你返回的字符串转为json字符串输出

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问