java
import com.alibaba.fastjson.JSONObject;
import com.alibaba.gts.flm.base.util.MysqlUtil;
import com.alibaba.gts.flm.base.util.StringUtils;
import java.util.Set;
public class Json转表结构 {
private static JSONObject j;
public static void main(String[] args) {
j = JSONObject.parseObject(s);
Set<String> keys = j.keySet();
StringBuffer ddl = new StringBuffer();
ddl.append("CREATE TABLE lkyw_vehicle_info (\n" +
" `pkid` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',\n" +
" `create_time` datetime DEFAULT NULL COMMENT '创建时间',\n" +
" `modify_time` datetime DEFAULT NULL COMMENT '修改时间',\n");
// 遍历键并获取其类型
for (String key : keys) {
Class<?> keyType = j.get(key).getClass();
String xhx = StringUtils.tuoFengToxiaHuaXian(key);
ddl.append(" `" + xhx + "` " + MysqlUtil.getMysqlType(getJavaObject(keyType.toString())) + " DEFAULT NULL COMMENT '" + "" + "',\n");
}
ddl.append(
" PRIMARY KEY (`pkid`)\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COMMENT='';");
System.out.println(ddl);
}
public static String getJavaObject(String kt) {
switch (kt) {
case "java.lang.String":
return "String";
case "java.lang.Integer":
case "java.lang.Long":
return "Long";
case "java.lang.Float":
case "java.lang.Double":
case "class java.math.BigDecimal":
return "Double";
default:
break;
}
return "String";
}
public static String s = "{\n" +
" \"age\": \"6\",\n" +
" \"name\": \"张三\",\n" +
" \"speed\": 553.8017520000001,\n" +
" \"lng\": 103.980244,\n" +
" \"lat\": 30.694589\n" +
" }";
}
MysqlUtil
java
import java.util.LinkedList;
import java.util.List;
/**
* @Author: liyue
* @Date: 2022/08/17/11:39
* @Description:
*/
public class MysqlUtil {
public static final List<String> types = new LinkedList<String>() {{
add("tinyint");
add("int");
add("integer");
add("bigint");
add("float");
add("double");
add("char");
add("varchar");
add("datetime");
add("text");
}};
public static String getJavaType(String mysqlType) {
switch (mysqlType) {
case "tinyint":
case "int":
case "integer":
return "Integer";
case "bigint":
return "Long";
case "float":
return "Float";
case "double":
return "Double";
case "text":
case "char":
case "varchar":
case "datetime":
return "String";
default:
throw new RuntimeException("未找到与java映射的类型");
}
}
public static String getMysqlType(String javaType) {
switch (javaType) {
case "String":
return "varchar(100)";
case "Long":
return "bigint";
case "Double":
return "double";
case "double":
return "Double";
default:
throw new RuntimeException("未找到与mysql映射的类型");
}
}
}
StringUtils