Java Object List Map 转Json学习

最近学习的Java object List Map转Json代码:


import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.model.JSONValue;

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


public class test {
    //java object转json
    public static String obj2Json(Object obj) throws MapperException {
        JSONValue jsonValue = JSONMapper.toJSON(obj);
        String jsonStr = jsonValue.render(false);
        return jsonStr;
    }
    //java list 转json
    public static String obj2Json(List<Class> list) throws MapperException {
        if (list == null || list.size() == 0) {
            return "{}";
        }
        StringBuilder jsonString = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i != 0) {
                jsonString.append(",");
            }
            Class cla = list.get(i);
            jsonString.append(obj2Json(cla));
            // jsonString.append(obj2Json(cla, false));
        }
        return jsonString.toString();
    }
    //java map 转json
    public static String obj2Json(Map<String, Class> map) throws MapperException {
        if (map == null || map.size() == 0) {
            return "{}";
        }
        StringBuilder jsonString = new StringBuilder();
        Set<String> keySet = map.keySet();
        boolean isFirst = true;
        for (String key : keySet) {
            if (isFirst) {
                isFirst = false;
            } else {
                jsonString.append(",");
            }
            Class cla = map.get(key);
            jsonString.append(obj2Json(cla));
        }
        return jsonString.toString();
    }
}

你可能感兴趣的:(java,json,Java)