为了补上一篇挖的坑,所以简单的改进了一下bean2Json的方法
上一篇在这里QAQ
废话不多说,代码很简单,下面直接上代码
package com.tfxing.index.common.utils.handle;
import com.tfxing.index.common.entity.converObjTest.Person;
import com.tfxing.index.common.entity.converObjTest.SecurityDeposit;
import org.junit.platform.commons.util.StringUtils;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.StringJoiner;
public class MyJsonUtilPlus {
/**
* 对象转json字符串
* @param t
* @param <T>
* @return
*/
public static <T> String toJson(T t) throws Exception{
StringJoiner jsonStr = new StringJoiner(",");
Class<?> clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
field.setAccessible(true);
String tempStr = "\""+field.getName()+"\":";
Object obj = field.get(t);
if (Objects.isNull(obj)) {
tempStr += "\"\"";
jsonStr.add(tempStr);
continue;
}
if(isNormal(obj)) {
tempStr += "\""+obj.toString()+"\"";
jsonStr.add(tempStr);
} else {
String fieldJson = toJson(obj);
tempStr += fieldJson;
jsonStr.add(tempStr);
}
}
return StringUtils.isNotBlank(jsonStr.toString()) ? "{"+jsonStr.toString()+"}" : "\"\"";
}
private static boolean isNormal(Object obj) {
if(obj.getClass().getName().startsWith("java")) {
return true;
} else {
return false;
}
}
测试
public static void main(String[] args) throws Exception{
Person person = new Person("tfxing","男",18);
person.setAmount(BigDecimal.valueOf(100));
Person personInner = new Person("tfxingInner","女",19);
person.setPersonInner(personInner);
person.setDeposit(new SecurityDeposit("test"));
System.out.println(toJson(person));
System.out.println(toJson(new Integer(10)));
}
}