java中jsonlab库的简单使用--把对象转换为json对象

package app.json;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.xml.XMLSerializer;

/**
 * 澶勭悊json鏁版嵁鏍煎紡鐨勫伐鍏风被
 *
 * @author 閲戜簯榫�
 * @Date 2013-3-31
 * @version 1.0
 */
public class JsonUtil {
    /**
     * 灏嗘暟缁勮浆鎹㈡垚String绫诲瀷鐨凧SON鏁版嵁鏍煎紡
     *
     * @param objects
     * @return
     */
    public static String array2json(Object[] objects){
        
        JSONArray jsonArray = JSONArray.fromObject(objects);
        return jsonArray.toString();
        
    }
    
    /**
     * 灏唋ist闆嗗悎杞崲鎴怱tring绫诲瀷鐨凧SON鏁版嵁鏍煎紡
     *
     * @param list
     * @return
     */
    public static String list2json(List list){
        
        JSONArray jsonArray = JSONArray.fromObject(list);
        return jsonArray.toString();
        
    }
    
    /**
     * 灏唌ap闆嗗悎杞崲鎴怱tring绫诲瀷鐨凧SON鏁版嵁鏍煎紡
     *
     * @param map
     * @return
     */
    public static String map2json(Map map){
        
        JSONObject jsonObject = JSONObject.fromObject(map);
        return jsonObject.toString();
        
    }
    
    /**
     * 灏哋bject瀵硅薄杞崲鎴怱tring绫诲瀷鐨凧SON鏁版嵁鏍煎紡
     *
     * @param object
     * @return
     */
    public static String object2json(Object object){
        
        JSONObject jsonObject = JSONObject.fromObject(object);
        return jsonObject.toString();
        
    }
    
    /**
     * 灏哫ML鏁版嵁鏍煎紡杞崲鎴怱tring绫诲瀷鐨凧SON鏁版嵁鏍煎紡
     *
     * @param xml
     * @return
     */
    public static String xml2json(String xml){
        
        JSONArray jsonArray = (JSONArray) new XMLSerializer().read(xml);
        return jsonArray.toString();
        
    }
    
    /**
      * 闄ゅ幓涓嶆兂鐢熸垚鐨勫瓧娈碉紙鐗瑰埆閫傚悎鍘绘帀绾ц仈鐨勫璞★級
      *
      * @param excludes
      * @return
    */
    public static JsonConfig configJson(String[] excludes) {
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(excludes);
        jsonConfig.setIgnoreDefaultExcludes(true);
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        return jsonConfig;
    }
    
}

posted @ 2019-12-23 23:59  sundaysjava  阅读(191)  评论(0)    收藏  举报