错误com.fasterxml.jackson.databind.exc.MismatchedInputException:由于输入结束而没有要映射的内容

时间:2018-04-13 12:55:50

标签: java json string jackson objectmapper

我试图转换下一个字符串:

"{ \"contacts\": [{\"name\":\"1\",\"phone\":\"+123456\"}]}"

到一些自定义对象:

public class CustomObject{

    private List<Contact> contacts;

    public CustomObject(){

    }

    public CustomObject(List<Contact> contacts) {
        this.contacts = contacts;
    }

    public List<Contact> getContactList() {
        return contacts;
    }

    public void setContactList(List<Contact> contacts) {
        this.contacts = contacts;
    }
}

此外,此CustomObject中还有另一个对象:

public class Contact {

    private String name;
    private String phone;

    public Contact() {
    }

    public Contact(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

现在,我正尝试执行以下操作:

private List<Contact> parseString(String jsonAsString) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    CustomObject customObject = mapper.readValue(jsonAsString, CustomObject .class);
    return customObject .getContactList();
}

但我收到了下一个错误:

com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
 at [Source: (String)""{ \"contacts\": [{\"name\":\"1\",\"phone\":\"+972545519713\"}]}""; line: 1, column: 1]

1 个答案:

答案 0 :(得分:5)

杰克逊聪明,但 聪明。

如果没有注释,则在反序列化期间无法识别您的公共设置器setContactList

您有两种选择:

  1. 使用@JsonProperty("contacts")
  2. 对其进行注释
  3. 将其更改为setContacts
  4. 其他选择包括更改您的JSON或使实际字段可访问 - 没有详细说明,因为它们很可能是错误的选择。

    另请考虑在其他地方修改您的代码,例如:对于getContactList getter,如果您计划序列化POJO的实例。