java JSON 序列化类(List 转String)

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by mi on 16-12-22.
 */
public class SerializationDefine {
    public static String segSymbols = "##segSymbols##";//分割符号

    public static String Object2String(Object obj) {
        Preconditions.checkArgument(obj != null, "序列化对象为null");
        return JSONObject.toJSONString(obj);
    }

    public static  T String2Object(String str, Class tClass) {
        return JSONObject.parseObject(str, tClass);
    }

    public static  String[] List2StringArray(List objects) {
        if (objects == null || objects.size() == 0) {
            return new String[]{};
        }

        String[] strArray = new String[objects.size()];
        for (int i = 0; i < objects.size(); i++) {
            strArray[i] = Object2String(objects.get(i));
        }

        return strArray;
    }

    public static  List StringArray2List(String[] strs, Class tClass) {
        if (strs == null || strs.length == 0) {
            return new ArrayList();
        }

        List objList = new ArrayList();
        for (int i = 0; i < strs.length; i++) {
            objList.add(String2Object(strs[i], tClass));
        }
        return objList;
    }

    public static  String List2Str(List objects) {
        String[] strings = List2StringArray(objects);
        if (strings == null || strings.length == 0) {
            return "";
        }
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < strings.length; i++) {
            if (i == 0) {
                stringBuffer.append(strings[i]);
            } else {
                stringBuffer.append(segSymbols + strings[i]);
            }
        }
        return stringBuffer.toString();
    }

    public static  List Str2List(String str, Class tClass) {
        if (Strings.isNullOrEmpty(str)) {
            return new ArrayList();
        }

        String[] strs = str.split(segSymbols);
        return StringArray2List(strs, tClass);
    }
}

 

转载于:https://www.cnblogs.com/tengpan-cn/p/6881927.html

你可能感兴趣的:(java JSON 序列化类(List 转String))