io.github.whimthen.kits.json.MyJson Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kits Show documentation
Show all versions of kits Show documentation
Easy to use java tool library.
package io.github.whimthen.kits.json;
import io.github.whimthen.kits.DateTimeKit;
import io.github.whimthen.kits.MapKit;
import io.github.whimthen.kits.ReflectKit;
import io.github.whimthen.kits.StringKit;
import io.github.whimthen.kits.log.Logger;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
/**
* @project: kits
* @created: with IDEA
* @author: nzlong
* @Date: 2019 01 24 10:13 | January. Thursday
*/
public class MyJson {
private final static String NULL = "null";
/**
* 将对象转换为json字符串
*
* @param object 资源对象
* @return 转换后的结果
*/
public static String toJSON(Object object) {
StringBuilder jsonString = new StringBuilder();
try {
if (Objects.isNull(object)) {
jsonString.append(NULL);
} else if (object instanceof BigDecimal) {
jsonString.append(((BigDecimal) object).toPlainString());
} else if (object instanceof Date) {
jsonString.append(DateTimeKit.formatToDefaultPattern((Date) object));
} else if (object instanceof Map) {
jsonString.append(MapKit.toJSON((Map, ?>) object));
} else if (object instanceof Collection) {
jsonString.append(collectionJson((Collection) object));
} else if (object.getClass().isArray()) {
Object[] arrayObject;
if (object.getClass().getComponentType().isPrimitive()) {
int length = Array.getLength(object);
arrayObject = new Object[length];
for (int i = 0; i < length; ++i) {
arrayObject[i] = Array.get(object, i);
}
} else {
arrayObject = (Object[]) object;
}
jsonString.append(arrayJson(arrayObject));
} else if (object instanceof Integer || object instanceof Double || object instanceof Float || object instanceof Boolean || object instanceof Long || object instanceof Short) {
jsonString.append(object);
} else if (object instanceof String || object instanceof StringBuilder) {
jsonString.append(object.toString());
} else if (object instanceof Class) {
jsonString.append(((Class) object).getName());
} else {
jsonString.append("{").append(complexObject(object)).append("}");
}
} catch (Exception ex) {
Logger.errorf("JSON formart error", ex);
}
return jsonString.toString();
}
/**
* 将对象属性转换为json
*
* @param object 对象
* @return 转换后的结果
* @throws IllegalAccessException 处理异常
*/
private static String complexObject(Object object) throws IllegalAccessException {
if (Objects.isNull(object)) {
return NULL;
}
StringBuilder json = new StringBuilder();
List fields = ReflectKit.getFields(object.getClass());
for (Field field : fields) {
field.setAccessible(true);
Class> type = field.getType();
if (Objects.nonNull(type)) {
String name = field.getName();
Object value = field.get(object);
json.append("\"").append(name).append("\": ");
if (BigDecimal.class.isAssignableFrom(type) || Integer.class.isAssignableFrom(type) || int.class == type || Double.class.isAssignableFrom(type) || double.class == type || Float.class.isAssignableFrom(type) || float.class == type
|| Long.class.isAssignableFrom(type) || long.class == type || Short.class.isAssignableFrom(type) || short.class == type || Boolean.class.isAssignableFrom(type) || boolean.class == type) {
json.append(value);
} else if (Date.class == type || String.class == type || Byte.class == type || byte.class == type || char.class == type || Character.class == type) {
if (value == null) {
json.append(NULL);
} else {
json.append("\"").append(value).append("\"");
}
} else if (Map.class.isAssignableFrom(type)) {
json.append(MapKit.toJSON((Map, ?>) value));
} else if (Collection.class.isAssignableFrom(type)) {
json.append(Objects.isNull(value) ? NULL : collectionJson((Collection) value));
} else if (type.isArray()) {
json.append(arrayJson((Object[]) value));
} else {
String obj = complexObject(value);
if (StringKit.isNullOrEmpty(obj) || obj.equals(NULL)) {
json.append(obj);
} else {
json.append("{").append(obj).append("}");
}
}
json.append(", ");
}
}
return json.deleteCharAt(json.lastIndexOf(",")).deleteCharAt(json.lastIndexOf(" ")).toString();
}
/**
* 将集合转换为json
*
* @param collection 任意集合对象
* @return 转换后的结果
*/
private static String collectionJson(Collection collection) {
return arrayJson(collection.toArray());
}
/**
* 将数组转换为json
*
* @param objects 任意数组
* @return 转换后的结果
*/
private static String arrayJson(Object[] objects) {
if (objects == null || objects.length <= 0) {
return NULL;
}
StringBuilder jsonString = new StringBuilder("[");
for (Object object : objects) {
if (object instanceof Collection || object.getClass().isArray()) {
jsonString.append(arrayJson((Object[]) object));
} else if (object instanceof String || object instanceof Date || object instanceof Boolean) {
jsonString.append("\"").append(toJSON(object)).append("\"").append(", ");
} else {
jsonString.append(toJSON(object)).append(", ");
}
}
return jsonString.deleteCharAt(jsonString.lastIndexOf(",")).deleteCharAt(jsonString.lastIndexOf(" ")).append("]").toString();
}
/**
* 格式化Json字符串
*
* @param jsonStr
* @return
*/
public static String prettyJson(String jsonStr) {
if (StringKit.isNullOrEmpty(jsonStr)) {
return null;
}
StringBuilder prettyJson = new StringBuilder();
if (jsonStr.startsWith("{")) {
prettyJson.append(prettyObj(jsonStr, 1));
} else if (jsonStr.startsWith("[")) {
prettyJson.append(prettyArr(jsonStr, 1));
} else {
prettyJson.append(jsonStr);
}
return prettyJson.toString();
}
/**
* 格式化对象Json
*
* @param json Json字符串
* @param indentCount 缩进
* @return 格式化后的字符串
*/
private static String prettyObj(String json, int indentCount) {
StringBuilder jsonStr = new StringBuilder();
if (StringKit.isNotNullOrEmpty(json)) {
jsonStr.append(json.charAt(0));
json = json.substring(1).trim();
int mCount = 1;
char lastEffective = '#';
for (; StringKit.isNotNullOrEmpty(json) ;) {
char jsonCh = json.charAt(0);
json = json.substring(1);
if ((jsonCh == ' ' && lastEffective == ',')) {
continue;
}
switch (jsonCh) {
case '\"':
if (mCount % 2 != 0 && lastEffective != ':') {
jsonStr.append("\n").append(StringKit.repeat("\t", indentCount)).append(jsonCh);
} else {
jsonStr.append(jsonCh);
}
mCount++;
break;
case ':':
jsonStr.append(jsonCh).append((lastEffective == '\"' && json.length() > 1 && json.charAt(0) != ' ') ? ' ' : "");
break;
case '[':
String substring = json.substring(0, json.indexOf(']') + 1);
Logger.debugf("subString = {}", substring);
jsonStr.append(prettyJson('[' + substring));
json = json.substring(json.indexOf(']') + 1);
break;
case '{':
String obj = json.substring(0, json.indexOf("}") + 1);
json = json.substring(json.indexOf("}") + 1);
int charCount = StringKit.getCharCount(obj, '{');
for (int i = 0; i < charCount; i++) {
obj += json.substring(0, json.indexOf("}") + 1);
json = json.substring(json.indexOf("}") + 1);
}
int leftCount = 0, rightCount = 0;
String jsonArr = null, oldObj = null;
boolean isArr = false;
if (obj.contains("[")) {
isArr = true;
oldObj = obj;
leftCount = StringKit.getCharCount(obj, '[');
rightCount = StringKit.getCharCount(obj, ']');
jsonArr = obj.substring(obj.indexOf("["));
obj = obj.substring(0, obj.indexOf("["));
}
Logger.debugf("obj = {}", obj);
jsonStr.append(prettyObj('{' + obj, indentCount + 1));
if (isArr && StringKit.isNotNullOrEmpty(jsonArr)) {
if (leftCount > rightCount) {
for (int i = 0; i < leftCount - rightCount; i++) {
jsonArr += json.substring(json.indexOf("]") + 1);
json = json.substring(json.indexOf("]") + 1);
}
} else {
jsonArr = oldObj.substring(oldObj.indexOf("["), oldObj.indexOf("]") + 1);
json = oldObj.substring(oldObj.indexOf("]") + 1) + json;
}
Logger.debugf("josn = {}", json);
jsonStr.append(prettyArr(jsonArr, indentCount + 1));
}
break;
case '}':
jsonStr.append("\n").append(indentCount - 1 == 0 ? "" : StringKit.repeat("\t", indentCount - 1)).append(jsonCh);
break;
default:
jsonStr.append(jsonCh);
break;
}
if (jsonCh != ' ') {
lastEffective = jsonCh;
}
}
}
return jsonStr.toString();
}
private static String prettyArr(String resource, int indentCount) {
if (StringKit.isNullOrEmpty(resource)) {
return "";
}
StringBuilder prettyJson = new StringBuilder();
for (char ch : resource.toCharArray()) {
switch (ch) {
case '[':
prettyJson.append(ch).append("\n").append(StringKit.repeat("\t", indentCount + 1));
break;
case '{':
String jsonObj = resource.substring(resource.indexOf("{"), resource.indexOf("}") + 1);
resource = resource.substring(resource.indexOf("}") + 1);
Logger.debugf("jsonObj = {}", jsonObj);
Logger.debugf("resource = {}", resource);
prettyJson.append(prettyObj(jsonObj, indentCount + 1));
break;
// case '\"':
// break;
default:
prettyJson.append(ch);
break;
}
}
return prettyJson.toString();
}
}