首页 > 解决方案 > 将字符串值转换为自定义对象列表

问题描述

我有一个字符串 [{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
}

有没有最佳的投射或转换方式?

标签: javajsonparsingcollectionsjava-11

解决方案


我认为仅使用 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());

推荐阅读