Issue
I have a String [{max=0.0, min=0.0, co=3.0},{max=0.0, min=0.0, co=3.0}]
I want to convert it to List<CustomObject>
where Custom Object is a Java class as
CustomObject{
Integer max;
Integer min;
Integer co;
//getter setter
}
Is there any optimal way to cast or convert?
Solution
I don't think there is a short way to do it using only the Java standard library. But if you use an external library like GSON, it's quite easy:
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());
Answered By - ZhekaKozlov
Answer Checked By - Willingham (JavaFixing Volunteer)