java中将数据封装为JSON包,可以使用java提供的jsonArray这个工具类进行转换,代码如下:
package com.json;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
public class JSONUtils
{
/**
*
* @author wangwei JSON工具类
* @param
*
*/
/***
* 将List对象序列化为JSON文本
*/
public static String toJSONString(List list)
{
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.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;
}
/***
* 将对象转换为Collection对象
* @param object
* @return
*/
public static Collection toCollection(Object object)
{
JSONArray jsonArray = JSONArray.fromObject(object);
return JSONArray.toCollection(jsonArray);
}
/***
* 将对象转换为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 data = new HashMap();
JSONObject jsonObject = JSONUtils.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