fastjson序列化

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.ParameterizedTypeImpl;
import com.topsoft.cms.core.dto.Result;

/**
 *
 * @author guokaige
 *
 */
public class FastJsonUtil {

	/**
	 * 转换json字符串 JSON也是一种序列化。
	 *
	 * @param object
	 * @return
	 */
	public static String fastJsonSerialize(Object object) {
		return JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect);
	}

	/**
	 * 字符串转对象
	 *
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static  T unFastJsonSerialize(String object, Class clazz) {
		T t = null;
		try {
			t = JSON.parseObject(object, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}
	
	public static  Result parseResult(String json, Class clazz) {
	    return JSONObject.parseObject(json, new TypeReference>(clazz) {
	    });
	}
	
	public static  Result> parseListResult(String json, Class clazz) {
	    return JSONObject.parseObject(json, buildType(Result.class, List.class, clazz));
	}

	private static Type buildType(Type... types) {
	    ParameterizedTypeImpl beforeType = null;
	    if (types != null && types.length > 0) {
	        for (int i = types.length - 1; i > 0; i--) {
	            beforeType = new ParameterizedTypeImpl(new Type[]{beforeType == null ? types[i] : beforeType}, null, types[i - 1]);
	        }
	    }
	    return beforeType;
	}
	

	public static  Map json2Map(String jsonStr) {
		Map params = JSONObject.parseObject(jsonStr, new TypeReference>(){});
		return params;
	}

    public static  List json2List(String jsonStr, Class classOft) {
		return JSON.parseArray(jsonStr, classOft);
    }




    public static void main(String[] args) {

		String jsonStr="{'code':'22','ip':'aa','address':'ss'}";
		Map map2=FastJsonUtil.json2Map(jsonStr);
		System.out.println(map2.size());

	}











}

 

你可能感兴趣的:(java)