I am trying to deserialize a json response from another API but i keep on getting indexoutofboundException. Below is my json response that i am trying to deserialize -
{
"data" : [ ],
"metadata" : {
"transactionId" : "cfba12f56eaf6f24"
}
}
For deserializing i am using below implementation -
ResponseEntity<String>response=restTemplate.exchange(meta_uri,HttpMethod.POST,httpEntity,String.class);
String source=response.getBody();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
DataResponse metaResponse=mapper.readValue(source,DataResponse.class);
DataResponse.class looks like this -
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import java.util.ArrayList;
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@ToString
public class DataResponse {
@JsonProperty
private ArrayList<APIData>data;
@JsonProperty
private MetaData metadata;
}
APIData.class looks like this -
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import java.util.*;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
public class APIData {
@JsonProperty
private Map<String,Object> key;
@JsonProperty
private List<String> contacts;
}
Basically my implementation works when the json response is like this -
{
"data": [
{
"key": "123",
"contacts": [
"jon_doe@email.com",
"jon1_do3@email.com"
]
}
],
"metadata": {
"transactionId": "11112233333"
}
}
but gives me indexOutofBoundException when data array inside the response is empty -
{
"data" : [ ],
"metadata" : {
"transactionId" : "cfba12f56eaf6f24"
}
}
I guess maybe data that post request return is wrong. I do a test with string as your said. it is work.
@Test
public void mapper() throws Exception{
String json = "{\n" +
" \"data\" : [ ],\n" +
" \"metadata\" : {\n" +
" \"transactionId\" : \"cfba12f56eaf6f24\"\n" +
" }\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
DataResponse metaResponse=mapper.readValue( json ,DataResponse.class);
System.out.println("=========" + metaResponse);
// output
// =========DataResponse(data=[], metadata=MetaData(transactionId=cfba12f56eaf6f24))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.