将字符串值转换为自定义对象列表

问题描述 投票:0回答:1

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

是否有最佳的转换或转换方式?

我有一个字符串[{max = 0.0,min = 0.0,co = 3.0},{max = 0.0,min = 0.0,co = 3.0}]我想将其转换为List 其中,自定义对象是Java类为CustomObject {Integer max; ...

json parsing collections java-11 objectmapper
1个回答
0
投票

我不认为仅使用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());
© www.soinside.com 2019 - 2024. All rights reserved.