当我们和JSON数据交互的时候,有时候就需要将JSON数据转成实体来操作的情况,这个时候,字段少还好,字段一多,我们手动创建就很麻烦了.有的同学就说了,IDEA有插件啊,插件好用的很.但是我就是想不安装插件,通过一个copy然后执行一下就能把实体生成出来了,这个时间比找插件安装重启项目要快吧,而且还是透明的,想要改哪个地方也方便,下面来看看我写的相关代码!
import com.alibaba.fastjson.JSONObject;
import com.xxj.demo.json.util.CustomIOUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* 将json格式字符串生成出实体字段
*
* @author xunjian.xiao
* @date 2022/11/11 15:51
*/
public class JsonToEntity {
/**
* 结果字符串
*/
private StringBuilder resultString = new StringBuilder("\n");
/**
* 给json的key-设置属性名
*/
private Map<String, String> fieldMap = new HashMap<>(16);
/**
* 给json的key-设置属性名
*
* @param key
* @param value
*/
public void fieldMapPut(String key, String value) {
this.fieldMap.put(key, value);
}
/**
* 给json的key-设置说明
*/
private Map<String, String> fieldDescriptionMap = new HashMap<>(16);
/**
* 给json的key-设置说明
*
* @param key
* @param value
*/
public void fieldDescriptionMapPut(String key, String value) {
this.fieldDescriptionMap.put(key, value);
}
/**
* 需要追加的注解,规则:{key}-为json中的key,{value}-为json中的value
* 例如:
* "@ExcelImport(value = \"{key}\",kv = \"\",required = true,maxLength = 255,unique = true)"
*/
private List<String> appendInterfaceList = new ArrayList<>(16);
public void appendInterfaceAdd(String interfaceStr) {
this.appendInterfaceList.add(interfaceStr);
}
/**
* 将json字符串转换成实体对象
*
* @param clazz class对象
* @param classDescription 对象说明
* @param json json字符串
* @author xunjian.xiao
* @date 2022/11/14 11:06
*/
public void toEntityOrUpdateFile(Class clazz, String classDescription, String json) {
String result = toEntity(clazz, classDescription, json);
CustomIOUtil.rewriteFirst(clazz, null, result);
}
/**
* 默认开启Lombok,swagger
*
* @param clazz class对象
* @param classDescription 对象说明
* @param json json字符串
* @return 生成结果字符串
* @author xunjian.xiao
* @date 2022/11/14 9:23
*/
public String toEntity(Class clazz, String classDescription, String json) {
return toEntity(clazz, classDescription, true, true, json);
}
/**
* 将json字符串转换成实体对象
*
* @param clazz class对象
* @param classDescription 对象说明
* @param swagger 是否开启swagger注释 默认关闭 swagger说明
* @param lombok 是否开启lombok简化代码 默认关闭 lombok 代码简化
* @param json json字符串
* @return
* @throws
* @author xunjian.xiao
* @date 2022/11/11 17:09
*/
public String toEntity(Class clazz, String classDescription, Boolean swagger, Boolean lombok, String json) {
if (clazz == null) {
System.out.println("请选择对象");
return null;
}
if (swagger == null) {
swagger = false;//默认关闭 swagger说明
}
if (lombok == null) {
lombok = false;//默认关闭 lombok 代码简化
}
if (lombok) {
resultString.append("@Data\n" +
"@Accessors(chain = true)");
}
if (swagger) {
resultString.append("@ApiModel(value = \"" + clazz.getSimpleName() + "\", description = \"" + classDescription + "\")\n");
}
resultString.append("public class " + clazz.getSimpleName() + "{\n");
Map<String, Object> stringStringMap = JSONObject.parseObject(json, Map.class);
for (Map.Entry<String, Object> entity : stringStringMap.entrySet()) {
resultString.append("\t");
String key = entity.getKey();
Object value = "";
if (ObjectUtils.isNotEmpty(entity.getValue())) {
value = entity.getValue();
}
String fieldDescription = fieldDescriptionMap.get(key);
String field = fieldMap.get(key);
field = Objects.isNull(field) ? key : field;
if (Objects.nonNull(fieldDescription)) {
//有说明
key = fieldDescription;
}
//注释
resultString.append(String.format("/**%s*/\n", key));
//扩展功能,追加注解
addInterface(key, value);
if (swagger) {
resultString.append("\t");
resultString.append(String.format("@ApiModelProperty(\"%s\")", key));
resultString.append("\n");
}
//校验格式
String type = typeHandle(key, value);
resultString.append("\t");
resultString.append(String.format("private %s %s;", type, field));
resultString.append("\n");
}
resultString.append("}");
return resultString.toString();
}
/**
* 字段类型格式处理
*
* @param key
* @param value
* @return {@link String}
* @throws
* @author xunjian.xiao
* @date 2022/11/14 9:22
*/
private String typeHandle(String key, Object value) {
String type = getType(value);
//if (key.contains("时间")) {
//type = LocalDateTime.class.getSimpleName();
//String a = String.format("@JsonFormat( pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n\t@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")");
//resultString.append("\t");
//resultString.append(a);
//resultString.append("\n");
//}
return type;
}
/**
* 添加要增加的注解
*/
private void addInterface(String key, Object value) {
for (String appendInterface : appendInterfaceList) {
resultString.append("\t");
appendInterface = appendInterface.replace("{key}", key);
appendInterface = appendInterface.replace("{value}", Objects.nonNull(value) ? value.toString() : StringUtils.EMPTY);
resultString.append(appendInterface);
resultString.append("\n");
}
}
/**
* 类型判断
*
* @param value 值
* @return {@link String}
* @throws
* @author xunjian.xiao
* @date 2022/11/11 15:57
*/
private String getType(Object value) {
//默认字符串格式
String type = String.class.getSimpleName();
if (value != null) {
type = value.getClass().getSimpleName();
}
return type;
}
/**
* 打印json格式相关功能字符串
*
* @param json
* @author xunjian.xiao
* @date 2022/11/14 11:27
*/
public static void prlintlnJsonMap(String json) {
Map<String, Object> stringObjectMap = JSONObject.parseObject(json, Map.class);
int i = 97;
for (Map.Entry<String, Object> a : stringObjectMap.entrySet()) {
System.out.println(String.format("jsonToEntity.fieldMapPut(\"%s\",\"%c\");", a.getKey(), i++));
}
}
}
package com.xxj.demo.json;
import com.alibaba.fastjson.JSONObject;
import com.xxj.demo.json.util.CustomIOUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* 将json格式字符串生成出实体字段
*
* @author xunjian.xiao
* @date 2022/11/11 15:51
*/
public class JsonToEntity {
/**
* 结果字符串
*/
private StringBuilder resultString = new StringBuilder("\n");
/**
* 给json的key-设置属性名
*/
private Map<String, String> fieldMap = new HashMap<>(16);
/**
* 给json的key-设置属性名
*
* @param key
* @param value
*/
public void fieldMapPut(String key, String value) {
this.fieldMap.put(key, value);
}
/**
* 给json的key-设置说明
*/
private Map<String, String> fieldDescriptionMap = new HashMap<>(16);
/**
* 给json的key-设置说明
*
* @param key
* @param value
*/
public void fieldDescriptionMapPut(String key, String value) {
this.fieldDescriptionMap.put(key, value);
}
/**
* 需要追加的注解,规则:{key}-为json中的key,{value}-为json中的value
* 例如:
* "@ExcelImport(value = \"{key}\",kv = \"\",required = true,maxLength = 255,unique = true)"
*/
private List<String> appendInterfaceList = new ArrayList<>(16);
public void appendInterfaceAdd(String interfaceStr) {
this.appendInterfaceList.add(interfaceStr);
}
/**
* 将json字符串转换成实体对象
*
* @param clazz class对象
* @param classDescription 对象说明
* @param json json字符串
* @author xunjian.xiao
* @date 2022/11/14 11:06
*/
public void toEntityOrUpdateFile(Class clazz, String classDescription, String json) {
String result = toEntity(clazz, classDescription, json);
CustomIOUtil.rewriteFirst(clazz, null, result);
}
/**
* 默认开启Lombok,swagger
*
* @param clazz class对象
* @param classDescription 对象说明
* @param json json字符串
* @return 生成结果字符串
* @author xunjian.xiao
* @date 2022/11/14 9:23
*/
public String toEntity(Class clazz, String classDescription, String json) {
return toEntity(clazz, classDescription, true, true, json);
}
/**
* 将json字符串转换成实体对象
*
* @param clazz class对象
* @param classDescription 对象说明
* @param swagger 是否开启swagger注释 默认关闭 swagger说明
* @param lombok 是否开启lombok简化代码 默认关闭 lombok 代码简化
* @param json json字符串
* @return
* @throws
* @author xunjian.xiao
* @date 2022/11/11 17:09
*/
public String toEntity(Class clazz, String classDescription, Boolean swagger, Boolean lombok, String json) {
if (clazz == null) {
System.out.println("请选择对象");
return null;
}
if (swagger == null) {
swagger = false;//默认关闭 swagger说明
}
if (lombok == null) {
lombok = false;//默认关闭 lombok 代码简化
}
if (lombok) {
resultString.append("@Data\n" +
"@Accessors(chain = true)");
}
if (swagger) {
resultString.append("@ApiModel(value = \"" + clazz.getSimpleName() + "\", description = \"" + classDescription + "\")\n");
}
resultString.append("public class " + clazz.getSimpleName() + "{\n");
Map<String, Object> stringStringMap = JSONObject.parseObject(json, Map.class);
for (Map.Entry<String, Object> entity : stringStringMap.entrySet()) {
resultString.append("\t");
String key = entity.getKey();
Object value = "";
if (ObjectUtils.isNotEmpty(entity.getValue())) {
value = entity.getValue();
}
String fieldDescription = fieldDescriptionMap.get(key);
String field = fieldMap.get(key);
field = Objects.isNull(field) ? key : field;
if (Objects.nonNull(fieldDescription)) {
//有说明
key = fieldDescription;
}
//注释
resultString.append(String.format("/**%s*/\n", key));
//扩展功能,追加注解
addInterface(key, value);
if (swagger) {
resultString.append("\t");
resultString.append(String.format("@ApiModelProperty(\"%s\")", key));
resultString.append("\n");
}
//校验格式
String type = typeHandle(key, value);
resultString.append("\t");
resultString.append(String.format("private %s %s;", type, field));
resultString.append("\n");
}
resultString.append("}");
return resultString.toString();
}
/**
* 字段类型格式处理
*
* @param key
* @param value
* @return {@link String}
* @throws
* @author xunjian.xiao
* @date 2022/11/14 9:22
*/
private String typeHandle(String key, Object value) {
String type = getType(value);
//if (key.contains("时间")) {
//type = LocalDateTime.class.getSimpleName();
//String a = String.format("@JsonFormat( pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n\t@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")");
//resultString.append("\t");
//resultString.append(a);
//resultString.append("\n");
//}
return type;
}
/**
* 添加要增加的注解
*/
private void addInterface(String key, Object value) {
for (String appendInterface : appendInterfaceList) {
resultString.append("\t");
appendInterface = appendInterface.replace("{key}", key);
appendInterface = appendInterface.replace("{value}", Objects.nonNull(value) ? value.toString() : StringUtils.EMPTY);
resultString.append(appendInterface);
resultString.append("\n");
}
}
/**
* 类型判断
*
* @param value 值
* @return {@link String}
* @throws
* @author xunjian.xiao
* @date 2022/11/11 15:57
*/
private String getType(Object value) {
//默认字符串格式
String type = String.class.getSimpleName();
if (value != null) {
type = value.getClass().getSimpleName();
}
return type;
}
/**
* 打印json格式相关功能字符串
*
* @param json
* @author xunjian.xiao
* @date 2022/11/14 11:27
*/
public static void prlintlnJsonMap(String json) {
Map<String, Object> stringObjectMap = JSONObject.parseObject(json, Map.class);
int i = 97;
for (Map.Entry<String, Object> a : stringObjectMap.entrySet()) {
System.out.println(String.format("jsonToEntity.fieldMapPut(\"%s\",\"%c\");", a.getKey(), i++));
}
}
}
package com.xxj.demo.json.util;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* 获取Java项目路径
*
* @author xunjian.xiao
* @date 2022/11/11 14:57
*/
public class JavaProjectPathUtil {
/**
* 获取当前类的所在工程真实路径
* @param clazz
* @return {@link String}
* @author xunjian.xiao
* @date 2022/11/14 9:35
*/
public static String getPath(Class clazz){
return clazz.getResource("").getPath().replace("target/classes","src/main/java")+File.separator+clazz.getSimpleName()+".java";
}
/**
* 获取类加载的根路径
* @param
* @return {@link String}
* @author xunjian.xiao
* @date 2022/11/11 14:58
*/
public String getProjectPathUrl(){
// 第一种:获取类加载的根路径 D:\git\daotie\daotie\target\classes
File f = new File(this.getClass().getResource("/").getPath());
System.out.println("获取类加载的根路径:"+this.getClass().getResource("/").getPath());
System.out.println(f);
// 获取当前类的所在工程路径; 如果不加“/” 获取当前类的加载目录 D:\git\daotie\daotie\target\classes\my
File f2 = new File(this.getClass().getResource("").getPath());
System.out.println("获取当前类的加载目录:"+this.getClass().getResource("").getPath());
System.out.println(f2);
// 第二种:获取项目路径 D:\git\daotie\daotie
File directory = new File("");// 参数为空
String courseFile = null;
try {
courseFile = directory.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(courseFile);
// 第三种: file:/D:/git/daotie/daotie/target/classes/
URL xmlpath = this.getClass().getClassLoader().getResource("");
System.out.println(xmlpath);
// 第四种: D:\git\daotie\daotie
System.out.println(System.getProperty("user.dir"));
/*
* 结果: C:\Documents and Settings\Administrator\workspace\projectName
* 获取当前工程路径
*/
// 第五种: 获取所有的类路径 包括jar包的路径
System.out.println(System.getProperty("java.class.path"));
return null;
}
}
public class DemoApplication {
public static void main(String[] args) {
JsonToEntity jsonToEntity = new JsonToEntity();
//可选:按需要在字段属性上追加的注解
jsonToEntity.appendInterfaceAdd("@ExcelImport(value = \"{key}\",required = true,unique = true)");
//可选:按需要重写属性名
jsonToEntity.fieldMapPut("身份证号码","a");
//User.class这个类需要手动先创建,创建后执行即可写入字段属性
jsonToEntity.toEntityOrUpdateFile(User.class,"用户信息","这里是json格式数据字符串");
}
}