我想使用Jackson将Map<String, String>
绑定到bean。这里的陷阱是并非所有字段都是集合,因此它不起作用。
我需要调整ObjectMapper以仅在相应的bean属性是集合时才绑定集合。
public class MapperTest {
public static class Person {
public String fname;
public Double age;
public List<String> other;
}
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Map<String, String[]> props = new HashMap<>();
props.put("fname", new String[] {"mridang"});
props.put("age", new String[] {"1"});
props.put("other", new String[] {"one", "two"});
mapper.convertValue(props, Person.class);
}
}
上面的示例不起作用,因为杰克逊希望所有字段都是集合。
我无法更改Map结构,因为这是我要处理的旧系统,因此我对Map<String, String[]>
颇为困惑
答案 0 :(得分:4)
您可以如下使用DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS
:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
Map<String, String[]> props = new HashMap<>();
props.put("fname", new String[] {"mridang"});
props.put("age", new String[] {"1"});
props.put("other", new String[] {"one", "two"});
Person person = mapper.convertValue(props, Person.class);