将字符串值转换为自定义对象列表
Convert String value into a list of custom objects
我有一个字符串 [{max=0.0, min=0.0, co=3.0},{max=0.0, min=0.0, co=3.0}]
我想将其转换为 List<CustomObject>
,其中自定义对象是 Java class 作为
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());
我有一个字符串 [{max=0.0, min=0.0, co=3.0},{max=0.0, min=0.0, co=3.0}]
我想将其转换为 List<CustomObject>
,其中自定义对象是 Java class 作为
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());