【问题标题】:Could not read JSON: Unrecognized field (...), not marked as ignorable无法读取 JSON:无法识别的字段 (...),未标记为可忽略
【发布时间】:2014-10-17 09:28:05
【问题描述】:

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

所以我使用 org.springframework.web.client.RestTemplate 从 http-request 获取 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


    【解决方案1】:

    您可以在 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() 方法?
    • 好吧,没关系,我想通了,但现在我得到了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 愿意分享吗?
    猜你喜欢
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    相关资源
    最近更新 更多