indexoutofboundexception

7xllpg7q  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(234)

我试图反序列化来自另一个api的json响应,但我不断得到indexoutofboundexception。下面是我试图反序列化的json响应-

{
  "data" : [ ],
  "metadata" : {
    "transactionId" : "cfba12f56eaf6f24"
  }
}

对于反序列化,我使用下面的实现-

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如下所示-

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如下所示-

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;

}

基本上,我的实现在json响应如下时工作-

{
  "data": [
    {
      "key": "123",
      "contacts": [
        "jon_doe@email.com",
        "jon1_do3@email.com"
      ]
    }
  ],
  "metadata": {
    "transactionId": "11112233333"
  }
}

但是当响应中的数据数组为空时,会给出indexoutofboundexception-

{
  "data" : [ ],
  "metadata" : {
    "transactionId" : "cfba12f56eaf6f24"
  }
}
6kkfgxo0

6kkfgxo01#

我想也许请求后返回的数据是错误的。我像你说的那样用字符串做测试。这是工作。

@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))
    }

相关问题