将List中的datas转换为json格式写入文件

时间:2024-01-10 14:48:14
private static boolean writeToTextFileByJson(List<Map<String, Object>> datas, String title, String columns,
String fileName, String encode) {
final BufferedWriter bw;
boolean flag = true;
try {
boolean hasExists = new File(fileName).exists();
if(!hasExists){
createLocDir(fileName);//创建目录
}
File f = new File(fileName);
bw = new BufferedWriter(new FileWriter(f, false));
final String[] allcolumns = columns.substring(0, columns.length()).split(",");
Map<String, Object> resultMap = new HashMap<String, Object>();
String mobile = "";
List<Map<String,Object>> columnList = new ArrayList<Map<String,Object>>(); //mobileMap.put("mobile", (String) m.get(allcolumns[0].toUpperCase()));
Object value ="";
for(Map<String, Object> map : datas) {
for (int i = 1; i < allcolumns.length; i++) {
String columnName = allcolumns[i];
Set<String> set = map.keySet();
if(set.contains(columnName)){
value = map.get(columnName);
}
mobile = (String) map.get(allcolumns[0].toUpperCase());
resultMap.put("mobile", mobile);
HashMap<String, Object> columnMap = new HashMap<String, Object>();
columnMap.put("colum_name", columnName);
columnMap.put("value", value);
columnList.add(columnMap);
resultMap.put("column", columnList);
String json = JsonUtil.toJson(resultMap).toString();
bw.write(json);
columnList.clear();
}
} if (bw != null) {
bw.close();
}
} catch (Exception e) {
flag = false;
LOG.error("createFile(" + fileName + ") error:", e);
e.printStackTrace();
}
return flag;
}