I am a new coder on Spring Boot. I was working on my project and get an error about reading the data file. Normally my code is longer. However, I prepared a sample code for you.
public static void main(String[] args) {
SpringApplication.run(BookApplication.class, args);
String url="http://localhost:8080/books/list";
RestTemplate restTemplate = new RestTemplate();
String resp = restTemplate.getForObject(url, String.class);
JsonParser springParser = JsonParserFactory.getJsonParser();
Map<String, Object> map = ((org.springframework.boot.json.JsonParser) springParser).parseMap(resp);
String mapArray[] = new String[map.size()];
System.out.println("Items found: " + mapArray.length);
int i = 0;
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
i++;
}
}
and my Json File which I wrote into the database:
[
{
"name": "Harry Potter",
}
]
So I have an error of:
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.Object,java.lang.Object>` out of START_ARRAY token
at [Source: (String)"[{"name":"Harry Potter"}]"; line: 1, column: 1]
How to fix this error?
As @deadshot pointed out, the response is not a Map of String, Object . Rather a list of maps.
And you can shorten your code by entirely removing the parsing logic (using JsonParser ) by using ParameterizedTypeReference like this:
String url="http://localhost:8080/books/list";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Map<String,String>>> response = restTemplate.exchange(url, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Map<String,String>>>() {
});
List<Map<String,String>> body = response.getBody();
Assert.assertEquals("Harry Potter",body.get(0).get("name"));
If however, you want to go in the JsonParser way,
String url="http://localhost:8080/books/list";
RestTemplate restTemplate = new RestTemplate();
String resp = restTemplate.getForObject(url, String.class);
JsonParser springParser = JsonParserFactory.getJsonParser();
List<Object> list = ((org.springframework.boot.json.JsonParser) springParser).parseList(resp);
System.out.println("Items found: " + list.size());
for (Object book : list) {
Map<String,String> bookMap = (Map<String,String>) book;
bookMap.forEach((key,val) -> System.out.println(key + " = " + val));
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments