java - 将字符串值转换为自定义对象列表
问题描述
我有一个字符串 [{max=0.0, min=0.0, co=3.0},{max=0.0, min=0.0, co=3.0}]
,我想将其转换为List<CustomObject>
自定义对象是 Java 类的位置
CustomObject{
Integer max;
Integer min;
Integer co;
//getter setter
}
有没有最佳的投射或转换方式?
解决方案
我认为仅使用 Java 标准库没有捷径可走。但是如果你使用像GSON这样的外部库,那就很简单了:
String str = "[{max=0.0, min=0.0, co=3.0},{max=0.0, min=0.0, co=3.0}]";
// Parse str to list of maps
List<Map<String, Double>> list = new Gson().fromJson(str, List.class);
// Convert list of maps to list of CustomObject
List<CustomObject> objects = list.stream().map(map -> {
CustomObject obj = new CustomObject();
obj.min = map.get("min").intValue();
obj.max = map.get("max").intValue();
obj.co = map.get("co").intValue();
return obj;
}).collect(Collectors.toList());
推荐阅读
- driver - 如何以非 root 用户身份运行 nomad raw_exec 任务
- angular - Angular(8.x)不提供文件上传进度
- machine-learning - Pytorch,预训练模型:如何同时使用特征和分类器
- javascript - 如何使用脚本在浏览器中读取 Inspect Element 数据
- c# - C# JSON 文件反序列化为多个对象
- python - 下一个陈述怎么可能是真的?
- c# - UWP:添加项目后显示ListView的垂直滚动条
- numpy - 在 Numpy 中检查一行是否提升,但忽略元素 = 0
- ios - 有没有一种简单的方法来遍历多维数组并在 Swift 中转换每个元素?
- html - 尝试更改表格边框,不会从当前大小更改