该方法可以将json字符串数据转换成集合对象。
String devInfoList = [{"devId":"869718026017001","cabinetId":17,"devType":13,"devTypeStr":"XXX","devName":"XALTE_2003A","cabinetNo":1,"cabinetDoorNo":3}];
List<BatchDevInDto> batchDevInDtoList = JSONObject.parseArray(devInfoList, BatchDevInDto.class);
BatchDevInDto类的字段要与Json对象的字段保持一致
@Data
public class BatchDevInDto {
private String devId;
private Integer cabinetId;
private Integer devType;
private Integer cabinetNo;
private Integer cabinetDoorNo;
private String devTypeStr;
private String devName;
}
如果直接使用String.valueof()方法,会破坏对象内部的结构。
以下面的代码为例:
List<String> typeList = Arrays.asList("数据集","组件","模型","损失函数","数据资源");
Map<String,String> map =new HashMap<>();
List<Map<String,String>> list = new ArrayList<>();
for(String t : typeList){
if("数据资源".equals(t) && "Task".equals(type))
continue;
map.clear();
map.put("type",t);
map.put("title",t);
map.put("description",t);
list.add(map);
}
String tmp2 = String.valueOf(list);
//此时tmp2的值为:[{description=数据资源, type=数据资源, title=数据资源}, {description=数据资源, type=数据资源, title=数据资源}, {description=数据资源, type=数据资源, title=数据资源}, {description=数据资源, type=数据资源, title=数据资源}, {description=数据资源, type=数据资源, title=数据资源}]
jsonObject.put("catalogue", JSONObject.parseArray(tmp2))
return new NormalRes(jsonObject);
从上图可以看到,tmp2字符串的key和value的外面的冒号没了,并且不是key = value的格式。此时无法正常使用parseArray函数。
因此,需要对原来的列表中的key和value的字符串做处理,如下面所示:
List<String> typeList = Arrays.asList("数据集","组件","模型","损失函数","数据资源");
Map<String,String> map =new HashMap<>();
List<Map<String,String>> list = new ArrayList<>();
for(String t : typeList){
if("数据资源".equals(t) && "Task".equals(type))
continue;
map.clear();
map.put("\"type\"","\"" + t + "\"");
map.put("\"title\"","\"" + t + "\"");
map.put("\"description\"","\"" + t + "\"");
list.add(map);
}
String tmp2 = String.valueOf(list).replaceAll("=",":");
//此时tmp2的值为:[{"type":"数据资源", "title":"数据资源", "description":"数据资源"}, {"type":"数据资源", "title":"数据资源", "description":"数据资源"}, {"type":"数据资源", "title":"数据资源", "description":"数据资源"}, {"type":"数据资源", "title":"数据资源", "description":"数据资源"}, {"type":"数据资源", "title":"数据资源", "description":"数据资源"}]scription:数据资源, type:数据资源, title:数据资源}]
jsonObject.put("catalogue", JSONObject.parseArray(tmp2))
return new NormalRes(jsonObject);
这样问题就解决了。
JSONObject用法: link.