java.lang.String out of START_ARRAY使用ObjectMapper将POJO转换为HasMap <string,string>时出错

时间:2017-12-27 19:53:26

标签: java jackson

@Builder
@Getter
public class POJOClass {
    @NonNull
    private List<String> states;

    @NonNull
    private String country;

    @NonNull
    private String capital;

    public Map<String,String> convertToMap() {
        TypeReference<HashMap<String, String>> hashMapType
                = new TypeReference<HashMap<String, String>>() {};
        return new ObjectMapper().convertValue(this, hashMapType);
    }
}

我正在尝试使用instance.convertToMap()将上述类的实例转换为HashMap<String,String>,但这会失败并显示错误

Can not deserialize instance of java.lang.String out of START_ARRAY token
    at [Source: N/A; line: -1, column: -1] (through reference chain: java.util.HashMap["states"])
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3605)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3546)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3534)

我相信这是因为当反序列化到map时没有转换为String。

有没有办法可以将POJO转换为Map<String,String>而我不想要Map<String, Object>类型?

1 个答案:

答案 0 :(得分:1)

由于TypeReference不是字符串,而是列表,因此您无法执行Map<String, String>类型的states,因此您可以将TypeReference更改为Map<String,Object>即使你有一个列表,或者你希望将来添加一个复杂的对象,这应该结束了

public Map<String, String> convertToMap() {
    TypeReference<HashMap<String, Object>> hashMapType = new TypeReference<HashMap<String, Object>>() {
    };
    return new ObjectMapper().convertValue(this, hashMapType);
}

<强>更新

您仍然可以将Map<String, String>作为方法convertToMap()

的返回类型

完整示例:

@Builder
@Getter
public class POJOClass {
    @NonNull
    private List<String> states;

    @NonNull
    private String country;

    @NonNull
    private String capital;

    public Map<String, String> convertToMap() {
        TypeReference<HashMap<String, Object>> hashMapType = new TypeReference<HashMap<String, Object>>() {
        };
        return new ObjectMapper().convertValue(this, hashMapType);
    }


    public static void main(String[] args) {
        POJOClass pojoClass = new POJOClass(Lists.newArrayList("a", "b", "c"), "England", "London");
        System.out.println(pojoClass.convertToMap());
    }
}