日期:2014-05-16  浏览次数:20306 次

集合转JSON的方法
import java.util.Collection;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
/**
 * 
 * <b>Summary: </b>
 *      TODO JAVA转换JSON的数据格式通用类 
 * <b>Remarks: </b>
 *        TODO 请在此处详细描述类的功能、调用方法、注意事项、以及与其它类的关系
 */
public class JavaConvertJSON
{
    /**
        * 把数据对象转换成json字符串 DTO对象形如:{"id" : idValue, "name" : nameValue, ...}
        * 数组对象形如:[{}, {}, {}, ...] map对象形如:{key1 : {"id" : idValue, "name" :
        * nameValue, ...}, key2 : {}, ...}
        * {status : 'success'}
        * @param object
        * @return
        */
    @SuppressWarnings("unchecked")
    public static String getJSONString(Object object)
    {
        String jsonString = null;
        //日期值处理器
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[] {"handler", "hibernateLazyInitializer"});
        jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonDateValueProcessor());
        if (object != null)
        {
            if (object instanceof Collection || object instanceof Object[])
            {
                jsonString = JSONArray.fromObject(object, jsonConfig).toString();
            }
            else
            {
                jsonString = JSONObject.fromObject(object, jsonConfig).toString();
            }
        }
        return jsonString == null ? "{}" : jsonString;
    }

}

?