com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token

浪子不回头ぞ 提交于 2020-07-06 03:02:18

问题


How to read below JSON using Jackson ObjectMapper? I have developed code but getting below error.

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
 at [Source: (File); line: 7, column: 19] (through reference chain: com.example.demo.resources.Orgnization["secondaryIds"])

JSON

{
  "id": "100000",
  "name": "ABC",
  "keyAccount": false,
  "phone": "1111111",
  "phoneExtn": "11",
  "secondaryIds": {
    "ROP": [
      "700010015",
      "454546767",
      "747485968",
      "343434343"
    ],
    "AHID": [
      "01122006",
      "03112001"
    ]
  }
}

回答1:


You need to enable ACCEPT_SINGLE_VALUE_AS_ARRAY feature. Probably in POJO you have a List but when there is only one element in a List JSON payload is generated without array brackets.

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.util.List;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./src/main/resources/test.json");

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

        Orgnization root = mapper.readValue(jsonFile, Orgnization.class);
        System.out.println(root);
    }
}


来源:https://stackoverflow.com/questions/58539657/com-fasterxml-jackson-databind-exc-mismatchedinputexception-cannot-deserialize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!