jsonspringrest

Could not read JSON: Unrecognized field (...), not marked as ignorable


Yeah, I know that this issue has been discussed a few times, but I didn't manage to solve my problem.

So I'm getting a JSONObject from a http-request using org.springframework.web.client.RestTemplate:

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

But I get this error:

    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)

I want to access a Rest-Api and the Json Objects can have different field names. I already tried @JsonIgnoreProperties(ignoreUnknown=true). But this won't work...

How do I get the response into a JSONObject?


Solution

  • You can use this with Jackson 2.0 :

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

    If your version is prior to 2.0 use :

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