简体   繁体   中英

Convert String value into a list of custom objects

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?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM