使用jackson将json对象的List转换为hashmap

Ysa*_*sak 6 java jackson objectmapper

有没有办法使用内置的Jackson功能,使用java将json对象列表转换为HashMap

说明:我需要解析的Json结构

{
    list:[
        {
            keyId : 1,
            keyLabel : "Test 1",
            valueId: 34,
            valueLabel: "Test Lable"
        },
        {
            keyId : 2,
            keyLabel : "Test 2",
            valueId: 35,
            valueLabel: "Test Lable"
        },
        {
            keyId : 3,
            keyLabel : "Test 3",
            valueId: 36,
            valueLabel: "Test Lable"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我期待的对象模型,

class Key{
    int keyId;
    String keyLable;

    hashCode(){
    return keyId.hashCode();
    }
}

class Value{
    int valueId;
    String valueLable;

    hashCode(){
    return valueId.hashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要将上面的json列表转换为这样的地图,

HashMap<Key,Value> map;
Run Code Online (Sandbox Code Playgroud)

M F*_*eed 1

我建议手动完成。你只需要写几行。就像是

    ObjectMapper jmap = new ObjectMapper();
    //Ignore value properties
    List<Key> keys = jmap.readValue("[{}, {}]", jmap.getTypeFactory().constructCollectionType(ArrayList.class, Key.class));
    //Ignore key properties
    List<Value> values = jmap.readValue("[{}, {}]", jmap.getTypeFactory().constructCollectionType(ArrayList.class, Value.class));

    Map<Key, Value> data = new HashMap<>();
    for (int i = 0; i < keys.size(); i++) {
        data.put(keys.get(i), values.get(i));
    }
Run Code Online (Sandbox Code Playgroud)

注意:您的 json 和模型中存在拼写不匹配(valueLabel != valueLable)。