Search code examples
jsonspringrestjacksonrestful-url

Parsing Json file using Spring RestTemplate


I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR.

I connect to URL and print the response:

BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        StringBuilder response = new StringBuilder("");
        String output;
        while ((output = br.readLine()) != null) {
            response.append(output);
        }

with this result:

{"data":[{"device":"18AE63","time":1494516023,"data":"3235","snr":"36.72","linkQuality":"GOOD"},{"device":"18AE63","time":1494515750,"data":"484f4c41","snr":"35.69","linkQuality":"GOOD"}],"paging":{}}

But when I use RestTemplate

RestTemplate restTemplate = new RestTemplate();

         List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();        
         MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

         converter.setSupportedMediaTypes(Arrays.asList(MediaType.ALL));         
         messageConverters.add(converter);  
         restTemplate.setMessageConverters(messageConverters);  

         MessageList messageList = 
                    restTemplate.getForObject(url, MessageList.class);

I got this error:

Exception in thread "main" org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON document: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@1d119efb; line: 1, column: 2]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@1d119efb; line: 1, column: 2]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:234)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:219)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:95)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:655)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
    at com.tdk.web.controllers.restful.client.RestTemplateGETExample.main(RestTemplateGETExample.java:49)
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@1d119efb; line: 1, column: 2]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1702)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:558)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:456)
    at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2689)
    at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:878)
    at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:772)
    at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3834)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3783)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2922)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:231)
    ... 6 more

the POJO:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"data",
"paging"
})
public class MessageList {

    @JsonProperty("data")
    private List<Message> data = null;
    @JsonProperty("paging")
    private Paging paging;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("data")
    public List<Message> getData() {
    return data;
    }

    @JsonProperty("data")
    public void setData(List<Message> data) {
    this.data = data;
    }

    @JsonProperty("paging")
    public Paging getPaging() {
    return paging;
    }

    @JsonProperty("paging")
    public void setPaging(Paging paging) {
    this.paging = paging;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
    return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
    this.additionalProperties.put(name, value);
    }

    @Override
    public String toString() {
        return "MessageList [data=" + data + ", paging=" + paging + ", additionalProperties=" + additionalProperties
                + "]";
    }
}

Solution

  • The response you're getting is HTML, not JSON.

    JsonParseException: Unexpected character ('<' (code 60))
    

    This usually means that your HTTP call got an HTML error response (think <html><h1>404 Not Found</h1>...</html>), hence the JSON parser complaining that the response is not valid JSON.