文章目录
根据JSON数据生成属性注释
需要引入阿里巴巴的fastjson.jar
可以使用hutool-all.jar
工具包的StrUtil.isBlank()
替换org.apache.commons.lang.StringUtils.isBlank()
package com.dms.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dms.common.util.CommonFun;
public class TestFun
{
public static void main(String[] args)
throws Exception
{
System.out.println("JSON格式化");
System.out.println("-----------------------------------------------------");
JSONObject json = getJsonInfo();
System.out.println(jsonFormat(1, json.toString()));
List<JSONObject> jsonList = getJsonCommentInfo(json);
System.out.println("JSON字段注释解析结果");
System.out.println("-----------------------------------------------------");
for (JSONObject obj : jsonList)
{
System.out.println(obj.getString("key") + ":" + obj.getString("datatype"));
}
}
public static JSONObject getJsonInfo()
{
JSONObject data = new JSONObject();
data.put("productname", "注射器");
JSONArray array = new JSONArray();
JSONObject linkproduct = new JSONObject();
linkproduct.put("productnorms", "30mm");
linkproduct.put("countunit", "只");
linkproduct.put("pakingcount", "5");
JSONObject companyproduct = new JSONObject();
companyproduct.put("supplyprice", "100");
companyproduct.put("transactioncode", "CN112302");
linkproduct.put("companyproduct", companyproduct);
array.add(linkproduct);
data.put("normsinfo", array);
JSONObject factory = new JSONObject();
factory.put("factoryname", "南京xxx厂**有限股份公司");
factory.put("phonenumber", "12345678910");
factory.put("manageuser", "张三");
data.put("factoryinfo", factory);
JSONArray numbers = new JSONArray();
numbers.add(541);
numbers.add(545);
numbers.add(55);
numbers.add(4);
numbers.add(64);
numbers.add(187);
numbers.add(64);
numbers.add(61);
numbers.add(29);
data.put("charts", numbers);
JSONObject json = new JSONObject();
json.put("msg", "成功");
json.put("code", 200);
json.put("data", data);
return json;
}
/**
* 根据JSON对象获取注释格式
*/
public static List<JSONObject> getJsonCommentInfo(Object json)
throws Exception
{
List<JSONObject> columnInfos = new ArrayList<JSONObject>();
if (json instanceof com.alibaba.fastjson.JSONObject)
{
JSONObject jsonObject = (JSONObject)json;
for (Map.Entry<String, Object> entry : jsonObject.entrySet())
{
String key = entry.getKey();
JSONObject obj = getJSONObjectForObject(jsonObject, key);
if (obj == null)
{
String value = entry.getValue().toString();
addJsonComment(columnInfos, key, isNumber(value) ? "number" : "varchar");
continue;
}
//对象格式
if (obj.getIntValue("objectType") == 1)
{
obj = obj.getJSONObject("value");
if (obj.isEmpty())
{
addJsonComment(columnInfos, key, "varchar");
continue;
}
List<JSONObject> list = getJsonCommentInfo(obj);
if (!list.isEmpty())
addJsonComment(columnInfos, key + ".", list);
else
addJsonComment(columnInfos, key, "varchar");
}
//数组格式
else
{
JSONArray array = obj.getJSONArray("value");
if (array.isEmpty())
{
addJsonComment(columnInfos, key, "varchar");
continue;
}
key += "[]";
Object aObj = array.get(0);
JSONArray jArray = CommonFun.parseJSONArray(aObj.toString());
JSONObject jObject = CommonFun.parseJSONObject(aObj.toString());
if (jArray.isEmpty() && jObject.isEmpty())
{
addJsonComment(columnInfos, key, isNumber(aObj.toString()) ? "number" : "varchar");
continue;
}
else if (!jObject.isEmpty())
{
List<JSONObject> list = getJsonCommentInfo(jObject);
if (!list.isEmpty())
addJsonComment(columnInfos, key + ".", list);
else
addJsonComment(columnInfos, key, "varchar");
continue;
}
else if (!jArray.isEmpty())
{
key += "[]";
List<JSONObject> list = getJsonCommentInfo(jArray);
if (!list.isEmpty())
addJsonComment(columnInfos, key + ".", list);
else
addJsonComment(columnInfos, key, "varchar");
}
}
}
}
//数组
else if (json instanceof com.alibaba.fastjson.JSONArray)
{
JSONArray array = (JSONArray)json;
String key = "[]";
Object aObj = array.get(0);
JSONArray jArray = CommonFun.parseJSONArray(aObj.toString());
JSONObject jObject = CommonFun.parseJSONObject(aObj.toString());
if (jArray.isEmpty() && jObject.isEmpty())
{
addJsonComment(columnInfos, key, isNumber(aObj.toString()) ? "number" : "varchar");
}
else if (!jObject.isEmpty())
{
List<JSONObject> list = getJsonCommentInfo(jObject);
if (!list.isEmpty())
addJsonComment(columnInfos, key + ".", list);
else
addJsonComment(columnInfos, key, "varchar");
}
else if (!jArray.isEmpty())
{
key += "[]";
List<JSONObject> list = getJsonCommentInfo(jArray);
if (!list.isEmpty())
addJsonComment(columnInfos, key + ".", list);
else
addJsonComment(columnInfos, key, "varchar");
}
}
else
{
throw new Exception("JSON格式不正确");
}
return columnInfos;
}
/**
* 根据集合批量接收属性注释
* @Author 朱腾
* @Time 2021年11月23日
*/
private static void addJsonComment(List<JSONObject> columnInfos, String key, List<JSONObject> list)
throws Exception
{
for (JSONObject detaiObj : list)
{
addJsonComment(columnInfos, key + detaiObj.getString("key"), detaiObj.getString("datatype"));
}
}
/**
* 增加属性注释
* @Author 朱腾
* @Time 2021年11月23日
*/
private static void addJsonComment(List<JSONObject> columnInfos, String key, String datatype)
throws Exception
{
JSONObject columnComment = new JSONObject();
columnComment.put("key", key);
columnComment.put("datatype", datatype);
columnInfos.add(columnComment);
}
/**
* 验证字符串是否为数字
* @Author 朱腾
* @Time 2021年1月25日
*/
public static boolean isNumber(String str)
throws Exception
{
if (StringUtils.isBlank(str))
return false;
//遍历
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
try
{
//转为数字,如果转数字的过程中出现了异常,则为非数字
Short.valueOf(String.valueOf(c));
}
catch (Exception e)
{
//字符非数字
return false;
}
}
return true;
}
/**
* 根据key值获取JSONObject中的JSON对象
* @author 朱腾
* @Time 2020年7月5日
*/
public static JSONObject getJSONObjectForObject(JSONObject jsonObject, String key)
{
JSONObject json = null;
try
{
JSONObject value = jsonObject.getJSONObject(key);
if (value == null)
return json;
json = new JSONObject();
json.put("value", value);
//1:JSONObject对象;2:JSONArray数组
json.put("objectType", 1);
return json;
}
catch (Exception e)
{
try
{
JSONArray value = jsonObject.getJSONArray(key);
if (value == null)
return json;
json = new JSONObject();
json.put("value", value);
//1:JSONObject对象;2:JSONArray数组
json.put("objectType", 2);
}
catch (Exception e1)
{
return json;
}
}
return json;
}
/**
* 格式化json数据 退格用\t 换行用\r
* @param formatType:格式化方式,默认控制台格式【1:控制台;2:HTML;】
* @param jsonStr:JSON字符串
* @Author 朱腾
* @Time 2020年11月14日
*/
public static String jsonFormat(Integer formatType, String jsonStr)
{
//去除特殊字符
jsonStr = Optional.ofNullable(jsonStr).orElse("").replace("\n", "").replace("\t", "");
String breakLine = "\n";
String space = "\t";
if (formatType != null && formatType == 2)
{
breakLine = "<br>";
space = " ";
}
int level = 0;
StringBuffer jsonForMatStr = new StringBuffer();
for (int i = 0; i < jsonStr.length(); i++)
{
char c = jsonStr.charAt(i);
if (level > 0 && breakLine.equals(
jsonForMatStr.substring((jsonForMatStr.length() - breakLine.length()), (jsonForMatStr.length() - 1))))
{
jsonForMatStr.append(getLevelStr(space, level));
}
switch (c)
{
case '{':
case '[':
jsonForMatStr.append(c + breakLine);
jsonForMatStr.append(getLevelStr(space, ++level));
break;
case ',':
jsonForMatStr.append(c + breakLine);
jsonForMatStr.append(getLevelStr(space, level));
break;
case '}':
case ']':
jsonForMatStr.append(breakLine);
level--;
jsonForMatStr.append(getLevelStr(space, level));
jsonForMatStr.append(c);
break;
default:
jsonForMatStr.append(c);
break;
}
}
return jsonForMatStr.toString();
}
/**
* JSON格式化,内部调用
* @Author 朱腾
* @Time 2020年11月14日
*/
private static String getLevelStr(String space, int level)
{
StringBuffer levelStr = new StringBuffer();
for (int levelI = 0; levelI < level; levelI++)
{
levelStr.append(space);
}
return levelStr.toString();
}
}