对象有时候打印出来的日志可能是以map的格式存在,转成json格式

package com.example.mybatiscodehelper.demo;

import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.io.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* @Author huangyanchang
* @Date 2022/9/8 22:29
*
* 用于将idNO=xxxx, userName=廖x文, cardNO=xxxxx, mobilePhone=xxxx, payChannelCode=ybp_1
* 成{"idNO":"xxxx","userName":"廖x文","cardNO":"xxxxx","mobilePhone":"xxxx","payChannelCode":"ybp_1"}
*
* @Version 1.0
*/
public class SpringConvertMap {

/**
* 用于将idNO=xxxx, userName=廖x文, cardNO=xxxxx, mobilePhone=xxxx, payChannelCode=ybp_1
* 转成{"idNO":"xxxx","userName":"廖x文","cardNO":"xxxxx","mobilePhone":"xxxx","payChannelCode":"ybp_1"}
* */
public static void main(String[] args) {
String str = "UserTest(id=1, name=hy)";
int i = str.indexOf("(");
char c = str.charAt(i);
String substring = str.substring(i + 1, str.lastIndexOf(")"));
System.out.println("subString: " + substring);
String lineTxt = readFile();
Map map = StringConvertMap(lineTxt);
System.out.println(new JSONObject(map));
System.out.println(substring);
}

private static String readFile() {
String lineTxt = "";
String str = "";
File file = new File("D:\\work\\demo\\src\\main\\resources\\log.txt");
if (file != null) {
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "utf-8")){
BufferedReader bufferedReader = new BufferedReader(reader);
if (file.isFile() && file.exists()) {
while ((lineTxt = bufferedReader.readLine()) != null) {
System.out.println("lineTex: " + lineTxt);
str = lineTxt;
}
} else {
System.out.println("读取文件出错!!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return str;
}

private static Map StringConvertMap(String toString) {
HashMap<Object, Object> map = new LinkedHashMap<>();
if (toString.contains("(") && toString.contains(")")) {
toString = toString.replace("(", "{");
toString = toString.replace(")", "}");
}
toString.trim();
String[] split = toString.split(",");
for (int i = 0; i < split.length; i++) {
String[] split1 = split[i].split("=");
map.put(split1[0], split1[1]);
}
return map;
}
}

posted @ 2022-09-08 22:28  宁山  阅读(569)  评论(0编辑  收藏  举报