如果我们使用lombok时,打印传入参数对象,这时输出格式是下面这种
public static class Square { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; } @Override
public String toString() { return "Square(width=" + this.width + ", height=" + this.height + ")"; } }
//Square(width=10, height=20)
如果我们需要转回成对象 ,这个时候就转不了,故简单写了一个转化成json的
/** * lombok tostring 转化后字符串转json * @param str * @param tClass * @param <T> * @return */ private static <T> String toJsonStr(String str, Class<T> tClass) { if (StringUtil.isEmpty(str)) { return null; } str = str.replace(")", "}"); while (str.indexOf("(") != -1) { int i = str.indexOf("("); str = str.substring(0, str.lastIndexOf("=", i) + 1) + "{" + str.substring(i + 1); } str = str.replace(" ", "") .replace("=", "\"=\"") .replace(",", "\",\"") .replace("\"null\"", "null") .replace("\"{", "{\"") .replace("}\"", "}") .replace("}", "\"}") .replace("\"}\"}","\"}}"); str = "\"" + str.replace("=", ":"); if ("\"{".equals(str.substring(0,2))){ str = "{\"" +str.substring(2) ; }else { str = str.substring(str.indexOf(":") + 1); } str = str.replace("\"null\"", "null"); JSONObject json = JSONObject.parseObject(str); if (tClass == null){ return str; } return JSONObject.toJSONString(json.toJavaObject(json, tClass)); } // 测试 public static void main(String[] args) { String str = "userDto=userDto(username=张三, age=20,abc=abc(id=abcdefg))"; System.out.println(toJsonStr(str,null)); } // 结果: {"username":"张三","age":"20","abc":{"id":"abcdefg"},"abc":"abc"}
//ps: 1.虽然不够优化,但是能用(临时要用写的)
2. 用到fastjson包
lombok @Data @ToString 调用tostring转化后的字符串转json字符串
原文:https://www.cnblogs.com/yjhkhnuje/p/12712913.html