Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token
JsonMappingException: out of START_ARRAY token
exception is thrown by Jackson object mapper as it's expecting an Object {}
whereas it found an Array [{}]
in response.
This can be solved by replacing Object
with Object[]
in the argument for geForObject("url",Object[].class)
.
References:
- Ref.1
- Ref.2
- Ref.3
Your JSON string is malformed: the type of center
is an array of invalid objects. Replace [
and ]
with {
and }
in the JSON string around longitude
and latitude
so they will be objects:
[
{
"name" : "New York",
"number" : "732921",
"center" : {
"latitude" : 38.895111,
"longitude" : -77.036667
}
},
{
"name" : "San Francisco",
"number" : "298732",
"center" : {
"latitude" : 37.783333,
"longitude" : -122.416667
}
}
]
I sorted this problem as verifying the json from JSONLint.com and then, correcting it. And this is code for the same.
String jsonStr = "[{\r\n" + "\"name\":\"New York\",\r\n" + "\"number\": \"732921\",\r\n"+ "\"center\": {\r\n" + "\"latitude\": 38.895111,\r\n" + " \"longitude\": -77.036667\r\n" + "}\r\n" + "},\r\n" + " {\r\n"+ "\"name\": \"San Francisco\",\r\n" +\"number\":\"298732\",\r\n"+ "\"center\": {\r\n" + " \"latitude\": 37.783333,\r\n"+ "\"longitude\": -122.416667\r\n" + "}\r\n" + "}\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo[] jsonObj = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of name is: " + itr.getName());
System.out.println("Val of number is: " + itr.getNumber());
System.out.println("Val of latitude is: " +
itr.getCenter().getLatitude());
System.out.println("Val of longitude is: " +
itr.getCenter().getLongitude() + "\n");
}
Note: MyPojo[].class
is the class having getter and setter of json properties.
Result:
Val of name is: New York
Val of number is: 732921
Val of latitude is: 38.895111
Val of longitude is: -77.036667
Val of name is: San Francisco
Val of number is: 298732
Val of latitude is: 37.783333
Val of longitude is: -122.416667