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

问题描述 投票:0回答:2

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

所以我使用 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 中?

json spring rest
2个回答
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);

0
投票

在类级别使用注释 @JsonIgnoreProperties(ignoreUnknown = true) 从包 org.codehaus.jackson.annotate.JsonIgnoreProperties 导入

© www.soinside.com 2019 - 2024. All rights reserved.