BEANUTIL 对象转JSON

时间:2023-03-09 23:08:33
BEANUTIL 对象转JSON
package cn.com.softmap.cache.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List; /**
*/
public class BeanUtil { private static final List<?> LEAVES = Arrays.asList(Boolean.class, Character.class, Byte.class, Short.class,
Integer.class, Long.class, Float.class, Double.class, Void.class, String.class, Date.class); /**
* 把Bean转换为字符串.
*
* @param obj
* @return String
*/
public static String toString(Object obj) {
if (obj == null)
return "null"; if (LEAVES.contains(obj.getClass())) {
return obj.toString();
}
if (obj instanceof Enum) {
return ((Enum<?>) obj).name();
}
if (obj.getClass().isArray()) {
Object[] oa = (Object[]) obj;
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i = 0; i < oa.length; i++)
sb.append(toString(oa[i]));
sb.append("]");
return sb.toString();
}
if (obj instanceof Collection) {
Collection<?> tempCol = (Collection<?>) obj;
Iterator<?> it = tempCol.iterator();
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i = 0; it.hasNext(); i++) {
if (i > 0) {
sb.append(",");
}
Object val = it.next();
sb.append(toString(val));
}
sb.append("]");
return sb.toString();
}
if (obj instanceof Class) {
return obj.getClass().getName();
}
StringBuilder sb = new StringBuilder();
sb.append(obj.getClass().getSimpleName()).append(":[");
for (Field f : obj.getClass().getDeclaredFields()) {
if (Modifier.isStatic(f.getModifiers()))
continue;
f.setAccessible(true);
sb.append(f.getName()).append(":");
try {
sb.append(toString(f.get(obj))).append(",");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
sb.append("]");
return sb.toString();
} /**
* 通过序列化进行深度复制
*
* @param obj
* @return Object
* @throws Exception
*/
public static Object deepClone(Object obj) throws Exception {
return deserialize(serialize(obj));
} /**
* @param obj
* @return byte[]
* @throws IOException
*/
public static byte[] serialize(Object obj) throws IOException {
if (null == obj) {
return null;
}
// 将对象写到流里
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
oo.flush();
return bo.toByteArray();
} /**
* @param bytes
* @return Object
* @throws Exception
*/
public static Object deserialize(byte[] bytes) throws Exception {
if (null == bytes || bytes.length == 0) {
return null;
}
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(bi);
return oi.readObject();
}
}