當發送JSON請求到服務器,我經常通過這條消息映入眼簾:Spring MVC的:通過客戶端發送的請求是語法不正確
通過客戶端發送的請求是語法不正確()。
通常這是一個不正確的屬性,因爲JSON映射到的對象不包含它,所以控制器沒有期望傳遞這個屬性。
查找參數是不必要的耗時 - 有沒有辦法獲得更多信息,甚至可能是異常的堆棧跟蹤?我試過在調試模式下運行,並且使用Jackson作爲我的JSON(de)serialiser。
當發送JSON請求到服務器,我經常通過這條消息映入眼簾:Spring MVC的:通過客戶端發送的請求是語法不正確
通過客戶端發送的請求是語法不正確()。
通常這是一個不正確的屬性,因爲JSON映射到的對象不包含它,所以控制器沒有期望傳遞這個屬性。
查找參數是不必要的耗時 - 有沒有辦法獲得更多信息,甚至可能是異常的堆棧跟蹤?我試過在調試模式下運行,並且使用Jackson作爲我的JSON(de)serialiser。
如果你的消費是從外部API,如果你想從不必要的元素屏蔽你的控制器中的數據/你不需要 你可以在POJO類使用下面的註釋
@JsonIgnoreProperties(ignoreUnknown = true)
,或者你的屬性可以將其設置爲全球
//jackson 2.0
jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
舊案例,我現在無關緊要,但對於其他類似麻煩的人,我會添加此條目。
檢查您有雙引號,而不是單引號。也嘗試逃離它們。
我用我的應用程序curl爲我的測試json請求。
我的JSON是這樣
{ 'name' : 'somedata', 'town':'some town' }
,它只是在我的眼前爆炸了。
「客戶端發送的請求在語法上不正確」是一般錯誤。所以我把它從單引號改爲雙引號,不行。然後,我嘗試在單引號前面加反斜槓,但仍然沒有。然後將其更改爲雙引號的反斜槓,然後立即顯示!
curl -i -H "Accept: application/json" -H "Content-Type: application/json" \
http://localhost:8077/dra/dump.json \
-X PUT -d "{\"name\" : \"My Name\", \"town\":\"My Town\"}"
大多數示例都使用'-d'{「x」:「y」} ',在Windows上它不起作用,我不得不用你的方式使它工作。 Thx發佈。 – Sydney
要獲取有關調試日誌的詳細信息/堆棧跟蹤反過來在log4j.properties春季網絡
log4j.logger.org.springframework.web =調試
非常感謝,這就是我正在尋找的(y) – webmaster
我面對同樣的錯誤,幾天後,最終啓用了@Farm提到的調試日誌,並能夠看到這個問題的原因。 我有一個Person對象被張貼在JSON從JSP到春天控制器,如下圖所示: -
@RequestMapping(value = "/get", method = RequestMethod.POST)
public @ResponseBody
Person getPerson(@RequestBody Person person) {
// System.out.println("inside get::::::::");
System.out.println("city:=" + person.getResidenceAddress().getCity()+" "
+ "name:= " + person.getFullName().getFirstName());
// Person prsn = personService.getPerson(person);
/*
* Person prsn = new Person(); prsn.setId(1); ResponseDecorator rd = new
* ResponseDecorator(prsn, true);
*/return person;
}
// Person Object
class Person{
private Name fullName;
private Address residenceAddress;
private Address mailingAddress;
private Gender gender;
private MaritalStatus maritalStatus;
private Integer creditRating;
}
//Address Object
public class Address {
private String streetNo;
private String streetName;
private String suburb;
private String city;
private String state;
private String country;
private Integer pinCode;
private AddressType addressType;
}
json post from jsp:-
//create JSON
var json = {
"id": id,
"fullName":{"firstName":firstName,"middleName":middleName,"surName": surName},
"residenceAddress":{ "streetNo": streetNo,
"streetName": streetName,
"suburb": suburb,
"city": city,
"state": state,
"country": country,
"pinCode": pincode
}
};
var dataString = JSON.stringify(json);
//alert(dataString);
$.ajax({
headers: {
Accept : "text/plain; charset=utf-8, application/json"},
url: "/myservice/get",
type: 'POST',
dataType: 'json',
//data : "{ }",
data: dataString,
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
上提交錯誤是400錯誤的請求,並沒有其他線索,爲什麼它是失敗的。 上啓用服務器上的調試模式下,我可以看到下面的錯誤堆棧跟蹤: -
**00:53:42,294 DEBUG RequestResponseBodyMethodProcessor:117 - Reading [com.foo.assignment.model.Person] as "application/json" using [org.springf[email protected]1813fb]
00:53:42,310 DEBUG ServletInvocableHandlerMethod:159 - Error resolving argument [0] [type=com.foo.assignment.model.Person]
HandlerMethod details:
Controller [com.foo.assignment.controller.PersonController]
Method [public com.foo.assignment.model.Person com.foo.assignment.controller.PersonController.getPerson(com.foo.assignment.model.Person)]
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: No suitable constructor found for type [simple type, class com.foo.assignment.model.Address]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: [email protected]; line: 1, column: 98] (through reference chain: com.foo.assignment.model.Person["residenceAddress"]); nested exception is org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.foo.assignment.model.Address]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: [email protected]; line: 1, column: 98] (through reference chain: com.foo.assignment.model.Person["residenceAddress"])
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:127)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:153)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:120)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:91)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:71)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:74)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:155)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.foo.assignment.model.Address]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: [email protected]; line: 1, column: 98] (through reference chain: com.foo.assignment.model.Person["residenceAddress"])
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:746)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1923)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:124)
... 37 more
00:53:42,310 DEBUG ExceptionHandlerException**
在地址對象添加一個默認的構造函數解決了這個錯誤。並且使用谷歌附加郵差(插件https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en)確實幫助我快速測試了我的更改。
問題出在您的POJO上,請將服務器日誌級別保持爲調試級別並檢查錯誤。這將主要與某些領域和領域類型不匹配有關。
歡迎來到StackOverflow。您必須更詳細地說明您的迴應,以更好地幫助用戶解決問題 – darkomen
使用嵌套類 時,也會發生此錯誤。
class One {
some code..
public class NestedOne {
private attr;
public NestedOne() {
// default constructor
}
}
}
,然後有 @RequestMapping(value = "/something") public String someControllerMethod(@RequestBody One.NestedOne nested) { ... }
傑克遜則無法識別NestedOne()作爲默認構造函數和搜索One.NestedOne()構造函數。
嘗試將'org.springframework'的登錄級別(假設您正在使用log4j或equiv。)更改爲'DEBUG'。 – nickdos
@nickdos歡呼,將嘗試 –
錯誤*客戶端發送的請求在語法上不正確「**在大多數情況下,意味着傑克遜無法脫鹽(將json字符串轉換爲對象),因爲缺省構造函數已丟失 在你的情況下,缺少默認的構造函數,你有參數化的構造函數,它覆蓋默認和傑克遜不能創建對象 – abosancic