你的位置:首页 > Java教程

[Java教程]JAVA JSON



public static String object2json(Object obj) {
StringBuilder json = new StringBuilder();
if (obj == null) {
json.append("\"\"");
} else if (obj instanceof String || obj instanceof Integer
|| obj instanceof Float || obj instanceof Boolean
|| obj instanceof Short || obj instanceof Double
|| obj instanceof Long || obj instanceof BigDecimal
|| obj instanceof BigInteger || obj instanceof Byte) {
json.append("\"").append(string2json(obj.toString())).append("\"");
} else if (obj instanceof Object[]) {
json.append(array2json((Object[]) obj));
} else if (obj instanceof List) {
json.append(list2json((List<?>) obj));
} else if (obj instanceof Map) {
json.append(map2json((Map<?, ?>) obj));
} else if (obj instanceof Set) {
json.append(set2json((Set<?>) obj));
} else {
json.append(bean2json(obj));
}
return json.toString();
}

public static String bean2json(Object bean) {
StringBuilder json = new StringBuilder();
json.append("{");
PropertyDescriptor[] props = null;
try {
props = Introspector.getBeanInfo(bean.getClass(), Object.class)
.getPropertyDescriptors();
} catch (IntrospectionException e) {
}
if (props != null) {
for (int i = 0; i < props.length; i++) {
try {
String name = object2json(props[i].getName());
String value = object2json(props[i].getReadMethod().invoke(
bean));
json.append(name);
json.append(":");
json.append(value);
json.append(",");
} catch (Exception e) {
logger.error("Exception raised-------->",e);
}
}
json.setCharAt(json.length() - 1, '}');
} else {
json.append("}");
}
return json.toString();
}

public static String list2json(List<?> list) {
StringBuilder json = new StringBuilder();
json.append("[");
if (list != null && list.size() > 0) {
for (Object obj : list) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}

public static String array2json(Object[] array) {
StringBuilder json = new StringBuilder();
json.append("[");
if (array != null && array.length > 0) {
for (Object obj : array) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}

public static String map2json(Map<?, ?> map) {
StringBuilder json = new StringBuilder();
json.append("{");
if (map != null && map.size() > 0) {
for (Object key : map.keySet()) {
json.append(object2json(key));
json.append(":");
json.append(object2json(map.get(key)));
json.append(",");
}
json.setCharAt(json.length() - 1, '}');
} else {
json.append("}");
}
return json.toString();
}

public static String set2json(Set<?> set) {
StringBuilder json = new StringBuilder();
json.append("[");
if (set != null && set.size() > 0) {
for (Object obj : set) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}

public static String string2json(String s) {
if (s == null)
return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
if (ch >= '\u0000' && ch <= '\u001F') {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
}
}
return sb.toString();
}

/***************************************************************************
* 将对象序列化为JSON文本
*
* @param object
* @return
*/
public static String toJSONString(Object object) {
JSONArray jsonArray = JSONArray.fromObject(object);

return jsonArray.toString();
}

/***************************************************************************
* 将JSON对象数组序列化为JSON文本
*
* @param jsonArray
* @return
*/
public static String toJSONString(JSONArray jsonArray) {
return jsonArray.toString();
}

/***************************************************************************
* 将JSON对象序列化为JSON文本
*
* @param jsonObject
* @return
*/
public static String toJSONString(JSONObject jsonObject) {
return jsonObject.toString();
}

/***************************************************************************
* 将对象转换为List对象
*
* @param object
* @return
*/
public static List toArrayList(Object object) {
List arrayList = new ArrayList();

JSONArray jsonArray = JSONArray.fromObject(object);
Iterator it = jsonArray.iterator();
while (it.hasNext()) {
JSONObject jsonObject = (JSONObject) it.next();

Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
Object key = keys.next();
Object value = jsonObject.get(key);
arrayList.add(value);
}
}

return arrayList;
}

/***************************************************************************
* 将对象转换为JSON对象数组
*
* @param object
* @return
*/
public static JSONArray toJSONArray(Object object) {
return JSONArray.fromObject(object);
}

/***************************************************************************
* 将对象转换为JSON对象
*
* @param object
* @return
*/
public static JSONObject toJSONObject(Object object) {
return JSONObject.fromObject(object);
}

/***************************************************************************
* 将对象转换为HashMap
*
* @param object
* @return
*/
public static HashMap toHashMap(Object object) {
HashMap<String, Object> data = new HashMap<String, Object>();
JSONObject jsonObject = toJSONObject(object);
Iterator it = jsonObject.keys();
while (it.hasNext()) {
String key = String.valueOf(it.next());
Object value = jsonObject.get(key);
data.put(key, value);
}

return data;
}

public static TreeMap toTreeMap(Object object) {
TreeMap<String, Object> data = new TreeMap<String, Object>();
JSONObject jsonObject = toJSONObject(object);
Iterator it = jsonObject.keys();
while (it.hasNext()) {
String key = String.valueOf(it.next());
Object value = jsonObject.get(key);
data.put(key, value);
}
return data;
}

public static LinkedHashMap toLinkedHashMap(Object object) {
LinkedHashMap<String, Object> data = new LinkedHashMap<String, Object>();
JSONObject jsonObject = toJSONObject(object);
Iterator it = jsonObject.keys();
while (it.hasNext()) {
String key = String.valueOf(it.next());
Object value = jsonObject.get(key);
data.put(key, value);
}
return data;
}
/***************************************************************************
* 将对象转换为List<Map<String,Object>>
*
* @param object
* @return
*/
// 返回非实体类型(Map<String,Object>)的List
public static List<Map<String, Object>> toList(Object object) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
JSONArray jsonArray = JSONArray.fromObject(object);
for (Object obj : jsonArray) {
JSONObject jsonObject = (JSONObject) obj;
Map<String, Object> map = new HashMap<String, Object>();
Iterator it = jsonObject.keys();
while (it.hasNext()) {
String key = (String) it.next();
Object value = jsonObject.get(key);
map.put((String) key, value);
}
list.add(map);
}
return list;
}

/***************************************************************************
* 将JSON对象数组转换为传入类型的List
*
* @param <T>
* @param jsonArray
* @param objectClass
* @return
*/
public static <T> List<T> toList(JSONArray jsonArray, Class<T> objectClass) {
return JSONArray.toList(jsonArray, objectClass);
}

/***************************************************************************
* 将对象转换为传入类型的List
*
* @param <T>
* @param
* @param objectClass
* @return
*/
public static <T> List<T> toList(Object object, Class<T> objectClass) {
JSONArray jsonArray = JSONArray.fromObject(object);

return JSONArray.toList(jsonArray, objectClass);
}

/***************************************************************************
* 将JSON对象转换为传入类型的对象
*
* @param <T>
* @param jsonObject
* @param beanClass
* @return
*/
public static <T> T toBean(JSONObject jsonObject, Class<T> beanClass) {
return (T) JSONObject.toBean(jsonObject, beanClass);
}

/***************************************************************************
* 将将对象转换为传入类型的对象
*
* @param <T>
* @param object
* @param beanClass
* @return
*/
public static <T> T toBean(Object object, Class<T> beanClass) {
JSONObject jsonObject = JSONObject.fromObject(object);

return (T) JSONObject.toBean(jsonObject, beanClass);
}

/***************************************************************************
* 将JSON文本反序列化为主从关系的实体
*
* @param <T>
* 泛型T 代表主实体类型
* @param <D>
* 泛型D 代表从实体类型
* @param jsonString
* JSON文本
* @param mainClass
* 主实体类型
* @param detailName
* 从实体类在主实体类中的属性名称
* @param detailClass
* 从实体类型
* @return
*/
public static <T, D> T toBean(String jsonString, Class<T> mainClass,
String detailName, Class<D> detailClass) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
JSONArray jsonArray = (JSONArray) jsonObject.get(detailName);

T mainEntity = toBean(jsonObject, mainClass);
List<D> detailList = toList(jsonArray, detailClass);

try {
BeanUtils.setProperty(mainEntity, detailName, detailList);
} catch (Exception ex) {
throw new RuntimeException("主从关系JSON反序列化实体失败!");
}

return mainEntity;
}

/***************************************************************************
* 将JSON文本反序列化为主从关系的实体
*
* @param <T>泛型T
* 代表主实体类型
* @param <D1>泛型D1
* 代表从实体类型
* @param <D2>泛型D2
* 代表从实体类型
* @param jsonString
* JSON文本
* @param mainClass
* 主实体类型
* @param detailName1
* 从实体类在主实体类中的属性
* @param detailClass1
* 从实体类型
* @param detailName2
* 从实体类在主实体类中的属性
* @param detailClass2
* 从实体类型
* @return
*/
public static <T, D1, D2> T toBean(String jsonString, Class<T> mainClass,
String detailName1, Class<D1> detailClass1, String detailName2,
Class<D2> detailClass2) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);

T mainEntity = toBean(jsonObject, mainClass);
List<D1> detailList1 = toList(jsonArray1, detailClass1);
List<D2> detailList2 = toList(jsonArray2, detailClass2);

try {
BeanUtils.setProperty(mainEntity, detailName1, detailList1);
BeanUtils.setProperty(mainEntity, detailName2, detailList2);
} catch (Exception ex) {
throw new RuntimeException("主从关系JSON反序列化实体失败!");
}

return mainEntity;
}

/***************************************************************************
* 将JSON文本反序列化为主从关系的实体
*
* @param <T>泛型T
* 代表主实体类型
* @param <D1>泛型D1
* 代表从实体类型
* @param <D2>泛型D2
* 代表从实体类型
* @param jsonString
* JSON文本
* @param mainClass
* 主实体类型
* @param detailName1
* 从实体类在主实体类中的属性
* @param detailClass1
* 从实体类型
* @param detailName2
* 从实体类在主实体类中的属性
* @param detailClass2
* 从实体类型
* @param detailName3
* 从实体类在主实体类中的属性
* @param detailClass3
* 从实体类型
* @return
*/
public static <T, D1, D2, D3> T toBean(String jsonString,
Class<T> mainClass, String detailName1, Class<D1> detailClass1,
String detailName2, Class<D2> detailClass2, String detailName3,
Class<D3> detailClass3) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);
JSONArray jsonArray3 = (JSONArray) jsonObject.get(detailName3);

T mainEntity = toBean(jsonObject, mainClass);
List<D1> detailList1 = toList(jsonArray1, detailClass1);
List<D2> detailList2 = toList(jsonArray2, detailClass2);
List<D3> detailList3 = toList(jsonArray3, detailClass3);

try {
BeanUtils.setProperty(mainEntity, detailName1, detailList1);
BeanUtils.setProperty(mainEntity, detailName2, detailList2);
BeanUtils.setProperty(mainEntity, detailName3, detailList3);
} catch (Exception ex) {
throw new RuntimeException("主从关系JSON反序列化实体失败!");
}

return mainEntity;
}

/***************************************************************************
* 将JSON文本反序列化为主从关系的实体
*
* @param <T>
* 主实体类型
* @param jsonString
* JSON文本
* @param mainClass
* 主实体类型
* @param detailClass
* 存放了多个从实体在主实体中属性名称和类型
* @return
*/
public static <T> T toBean(String jsonString, Class<T> mainClass,
HashMap<String, Class> detailClass) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
T mainEntity = toBean(jsonObject, mainClass);
for (Object key : detailClass.keySet()) {
try {
Class value = (Class) detailClass.get(key);
BeanUtils.setProperty(mainEntity, key.toString(), value);
} catch (Exception ex) {
throw new RuntimeException("主从关系JSON反序列化实体失败!");
}
}
return mainEntity;
}

public static String to // new一个 StringBuilder 用来接收要传递的 StringBuilder strBder = new StringBuilder();
PrintWriter writer = null;

String resultName = null;
String resultCount = null;

strBder.append("<? strBder.append("<graph caption=\""+reportName+"\" " +
"showNames=\"1\" decimalPrecision=\"1\" numberFormatScale=\"1\" baseFontSize=\"14\"" +
"formatNumber=\"1\" showValues=\"0\" >" );

for(int i=0;i<list.size();i++){
Map currMap = (Map)list.get(i);
resultName = currMap.get("resultName").toString();

resultCount = currMap.get("resultCount").toString();

strBder.append("<set name=\""+resultName+"\" value=\""+resultCount+"\" />");

}

strBder.append("</graph>");
return strBder.toString();
}