无法读取JSON:无法识别的字段(...),未标记为可忽略

时间:2014-10-17 09:28:05

标签: json spring rest

是的,我知道这个问题已经讨论了几次,但我没有设法解决我的问题。

所以我使用 org.springframework.web.client.RestTemplate从请求获取JSONObject:

JSONObject j = RestTemplate.getForObject(url, JSONObject.class);

但是我收到了这个错误:

    Exception in thread "main" org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized field "uri" (Class org.json.JSONObject), not marked as ignorable
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@6f526c5f; line: 2, column: 12] (through reference chain: org.json.JSONObject["uri"]); nested exception is org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "uri" (Class org.json.JSONObject), not marked as ignorable
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@6f526c5f; line: 2, column: 12] (through reference chain: org.json.JSONObject["uri"])
    at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readJavaType(MappingJacksonHttpMessageConverter.java:181)
    at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.read(MappingJacksonHttpMessageConverter.java:173)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:94)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:517)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:472)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:237)

我想访问Rest-Api,Json对象可以有不同的字段名称。 我已经尝试@JsonIgnoreProperties(ignoreUnknown=true)了。但这不起作用......

如何将响应转换为JSONObject?

2 个答案:

答案 0 :(得分:5)

你可以在Jackson 2.0中使用它:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

如果您的版本高于2.0,请使用:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(
DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

答案 1 :(得分:0)

org.codehaus.jackson.JsonParseException:意外字符(' h'(代码104)):预期有效值(数字,字符串,数组,对象,' true', ' false'或' null')

**注意:**您收到错误是因为您没有使用正确的JSON发送数据 格式。