java - java - 如何使用Java中的Jackson将地图中的逗号分隔字符串转换为对象中的Set
问题描述
我正在运行下一个程序:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Test {
private static class Shape {
private String name;
private Set<String> colors;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<String> getColors() {
return colors;
}
public void setColors(Set<String> colors) {
this.colors = colors;
}
}
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> attributes = new HashMap<>();
attributes.put("name", "table");
attributes.put("colors", "blue,green,red,black");
Shape shape = objectMapper.convertValue(attributes, Shape.class);
}
}
这里是 pom.xml 中的依赖项:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9.3</version>
</dependency>
</dependencies>
我得到了下一个错误:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot deserialize instance of `java.util.HashSet` out of VALUE_STRING token
at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.company.test.Test$Shape["colors"])
at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3751)
at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3669)
at com.company.test.Test.main(Test.java:36)
我尝试更改为:
attributes.put("colors", "[blue,green,red,black]");
AND
attributes.put("colors", "[\"blue\",\"green\",\"red\",\"black\"]");
但它不起作用。解决方法可以是下一个:
...
Set<String> colors = new HashSet<>();
colors.add("blue");
colors.add("green");
colors.add("red");
colors.add("black");
attributes.put("colors", colors);
...
但是,当前实现不允许该解决方案。您是否想象过如何使用不同的方法来实现?
解决方案
您可以CsvMapper
从jackson-dataformats-text库中使用。此外,您需要先反序列String
化为Set<String>
,构建 aMap
并将其转换为Shape
最后:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class CsvApp {
public static void main(String[] args) throws JsonProcessingException {
CsvMapper mapper = new CsvMapper();
String array = "blue,green,red,black";
Map<String, Object> attributes = new HashMap<>();
attributes.put("name", "table");
attributes.put("colors", mapper.readValue(array, new TypeReference<Set<String>>() {}));
Shape shape = mapper.convertValue(attributes, Shape.class);
System.out.println(shape);
}
}
推荐阅读
- opencv - Opencv triangulatePoints 函数没有给出世界单位的距离
- powerbi - 将单行员工记录转换为透视 Sankey 布局
- macos - 如何修复我的期望脚本以进行 scp 下载?
- ios - 调整单元格大小时如何使表格视图动画平滑
- c - 左对齐的字符串在下一行打印出来并且不正确
- java - 隐式转换与显式转换
- angular - Angular 模板中的 PhpStorm 错误:未解析的管道
- layout - Flutter中的基本对齐文本和虚线
- javascript - nodejs 为什么在调用我的 lambda 函数时出现错误“任务在 6.01 秒后超时”?
- c++ - Qt Window 标志设置为 Qt::WindowStaysOnTopHint 但不工作