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

5

嗯,我知道这个问题已经被讨论了几次,但我还是没能解决我的问题。

所以我正在使用org.springframework.web.client.RestTemplate从http请求中获取一个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?

1个回答

6
你可以使用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);

我已经了解了这个,但是我应该如何使用readValue()方法呢? - Maik
好的,没关系,我已经解决了,但现在我遇到了一个异常:Exception in thread "main" org.codehaus.jackson.JsonParseException: Unexpected character ('h' (code 104)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') - Maik
抱歉回答这么多……我正在努力解决问题并已经成功运行了。暂时先谢谢! - Maik
@Maik 你能分享一下吗? - Luis Mauricio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接