如何使用 Jackson 将 Map<String、String[]> 参数绑定到 bean?



我想使用Jackson将Map<String, String>绑定到bean。这里的陷阱是,并不是所有的字段都是集合,所以它不起作用。

当对应的bean属性是集合时,我需要调整ObjectMapper以仅绑定集合。

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);
}
}

上面的例子不起作用,因为Jackson希望所有字段都是集合。


我无法更改Map结构,因为这是我正在处理的遗留系统,所以我几乎只能使用Map<String, String[]>

您可以使用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);

最新更新