Java 如何使用Jackson绑定地图<;字符串,字符串[]>;一个bean的参数?
我想使用Jackson将Java 如何使用Jackson绑定地图<;字符串,字符串[]>;一个bean的参数?,java,jackson,Java,Jackson,我想使用Jackson将映射绑定到bean。这里的陷阱是,并不是所有字段都是集合,所以它不起作用 当对应的bean属性是集合时,我需要调整ObjectMapper以仅绑定集合 public class MapperTest { public static class Person { public String fname; public Double age; public List<String> other; }
映射
绑定到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);
}
}
公共类映射测试{
公共静态类人员{
公共字符串fname;
公众双倍年龄;
其他公开名单;
}
公共静态void main(字符串[]args){
ObjectMapper mapper=新的ObjectMapper();
Map props=newhashmap();
put(“fname”,新字符串[]{“mridang”});
put(“age”,新字符串[]{“1”});
put(“其他”,新字符串[]{“一”,“二”});
转换值(道具,Person.class);
}
}
上面的示例不起作用,因为Jackson希望所有字段都是集合
我无法更改地图结构,因为这是我正在处理的一个遗留系统,所以我几乎只能使用您可以使用的
Map
,如下所示:
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);
ObjectMapper mapper=new ObjectMapper();
启用(反序列化功能。展开单个值数组);
Map props=newhashmap();
put(“fname”,新字符串[]{“mridang”});
put(“age”,新字符串[]{“1”});
put(“其他”,新字符串[]{“一”,“二”});
Person=mapper.convertValue(道具,Person.class);
你提供的是收藏品,为什么Jackson会期望其他的呢?这里有一点背景故事。我现在使用的是一个传统的web框架,它将所有URL查询参数公开为一个黑客地图。我想迁移到标准化的ser-deser库,这似乎是我唯一的出路。这很接近,但你需要另一种方式;)我无法检查,但您可以在非数组字段上尝试@JsonFormat(shape=JsonFormat.shape.Array)
。很好,我不知道它的存在,并且设法找到了它,只有这样我才能走上正轨;)