`
sanshizi
  • 浏览: 83262 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

将java类生成json

    博客分类:
  • Java
阅读更多
package utils;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Administrator
 */
public class JSONUtil {

    /**
     * 字段过滤模式
     */
    public static final int INCLUDE = 0;
    public static final int REMOVE = 1;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     *
     * @param <T>
     * @param o
     * @param maxLength 如果是String型,字符串的最大截取长度
     * @param createSub 如果是集合,那么集合中的子对象是否也生成json字串
     * @param Map<String, List<String&rt;&rt; filterMap :对指定的类进行字段的过滤
     * @param pattern 字段过滤模式:0(NOT)-只考虑已经列出的字段,1(REMOVE)-去除已经列出的字段
     * @return
     */
    public static <T> String toJSON(T o, int maxLength, boolean createSub, Map<String, String> filterMap, int pattern) {
        if (o == null) {
            return "null";
        }
        return toJSONx(o, o.getClass(), maxLength, createSub, filterMap, pattern, null);
    }

    public static <T> String toJSON(T o) {
        return JSONUtil.toJSON(o, 0, false, null, 0);
    }

    public static <T> String toJSON(T o, int maxLength) {
        return JSONUtil.toJSON(o, maxLength, false, null, 0);
    }

    /**
     *
     * @param <T>
     * @param o 要转为json的对象
     * @param clazz o的类型,关键时刻,用于强制转换o的类型T为V
     * @param maxLength
     * @param createSub
     * @param filterMap
     * @param pattern
     * @param olist 存储已经处理过的对象,在list中的索引越高,层级越深
     * @return
     */
    private static <T> String toJSONx(T o, Class clazz, int maxLength, boolean createSub, Map<String, String> filterMap, int pattern, List<Object> olist) {
        String s = "";
        String c = "";
        try {
            if (o != null) {
                /**
                 * 不知道是何种类型的,利用反射得到元素,但是防止循环引用,此处做一次检查,
                 * 有个缺陷,如果元素对相同对象引用两次,则只会自动转为不考虑下级对象模式,防止死循环
                 */
                olist = olist == null ? (new ArrayList<Object>()) : olist;
                for (Object vo : olist) {
                    if (vo == o) {
                        createSub = false;
                        S.p("-----(toJSONx)已爬取过,再爬取一次, 但不再考虑下级");
                        break;
                    } else {
                        olist.add(o);
                    }
                }

                c = o.getClass().getName();

                //检查各种类型情况
                if (String.class.getName().equals(c)) {
                    return S.addDoubleQuot(maxLength > 0 ? S.left(o + "", maxLength) : (o + ""));
                } else if (o instanceof Number
                        || Boolean.class.getName().equals(c)
                        || boolean.class.getName().equals(c)) {
                    return o + "";
                } else if (o instanceof Date) {
                    return S.addDoubleQuot(sdf.format((Date) o));
                } else if (o instanceof Collection) {
                    s += "[";
                    int k = 0;
                    for (Object oo : (Collection) o) {
                        if (createSub) {
                            if (k++ > 0) {
                                s += ", ";
                            }
                            s += toJSONx(oo, oo.getClass(), maxLength, createSub, filterMap, pattern, olist);
                        } else {
                            s += getJsonString(oo, maxLength);
                        }
                    }
                    s += "]";

                } else if (Map.class.getName().equals(c) || HashMap.class.getName().equals(c)) {
                    s += "{";
                    int k = 0;
                    Map map = (HashMap) o;
                    for (Object oo : map.keySet()) {
                        if (k++ > 0) {
                            s += ", ";
                        }
                        s += "\"" + S.inDoubleQuot(oo + "") + "\":";
                        if (map.get(oo) == null) {
                            s += "null";
                        } else {
                            if (createSub) {
                                s += toJSONx(map.get(oo), oo.getClass(), maxLength, createSub, filterMap, pattern, olist);
                            } else {
                                s += getJsonString(map.get(oo), maxLength);
                            }
                        }
                    }
                    s += "}";
                } else if (o != null && o.getClass().isArray()) {
                    s += "[";
                    for (int k = 0; k < Array.getLength(o); k++) {
                        if (createSub) {
                            if (k > 0) {
                                s += ", ";
                            }
                            s += toJSONx(Array.get(o, k), clazz, maxLength, createSub, filterMap, pattern, olist);
                        } else {
                            s += "getJsonString(Array.get(o, k), maxLength)";
                        }
                    }
                    s += "]";
                } else {
                    String[] fieldNames = null;
                    if (filterMap != null && filterMap.get(o.getClass().getName() + "") != null) {
                        fieldNames = S.xstring(filterMap.get(o.getClass().getName() + ""), "").split(",");
                        S.p("----o.getClass():" + o.getClass().getName() + "=" + filterMap.get(o.getClass().getName() + ""));
                    }
                    List<Field> flist = S.getAllFieldsIncludeSuper(clazz);
                    String get = "";
                    Method method;
                    Object oo = null;
                    if (flist.isEmpty()) {
                        s = "{}";
                    } else {
                        int k = 0;
                        s += "{";
                        for (Field f : flist) {
                            c = f.getType().getName();
                            //字段过滤
                            if (fieldNames != null) {
                                if (pattern == REMOVE && S.isInArray(f.getName(), fieldNames)) {//去除模式
                                    continue;
                                } else if (pattern == INCLUDE && !S.isInArray(f.getName(), fieldNames)) {//包含模式
                                    continue;
                                }
                            }

                            //看有没有get方法把值给取出来,无法取值的,跳过
                            get = S.markMethodString(f, "get");
                            if (S.hasMethod(o.getClass(), get)) {
                                method = o.getClass().getMethod(get);
                                oo = method.invoke(o);
                            } else {
                                continue;
                            }

                            if (k++ > 0) {
                                s += ", ";
                            }

                            s += S.addDoubleQuot(f.getName()) + " : ";
                            //如果抓取下级, 则递归抓取
                            if (createSub) {
                                s += toJSONx(oo, f.getType(), maxLength, createSub, filterMap, pattern, olist);
                            } else {
                                s += getJsonString(oo, maxLength);
                            }
                        }
                        s += "}";
                    }
                }

            } else {
                s += null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    public static String x(int c) {
        String s = "";
        while (c-- > 0) {
            s += "\t";
        }
        return s;
    }

    /**
     * 生成最大长度为maxLength的字符串,如果maxLength为0,则全部输出
     *
     * @param <T>
     * @param o
     * @param maxLength
     * @return
     */
    public static <T> String getJsonString(T o, int maxLength) {
        //检查各种类型情况
        String s = "", c = "";
        if (o == null) {
            return "null";
        } else if (o instanceof Number
                || Boolean.class.getName().equals((c = o.getClass().getName()))
                || boolean.class.getName().equals(c)) {
            s = o + "";
            s = maxLength > 0 ? S.left(s, maxLength) : s;
        } else if (String.class.getName().equals(c)) {
            s = o + "";
            s = S.addDoubleQuot(maxLength > 0 ? S.left(s, maxLength) : s);
        } else if (o instanceof Date) {
            s = sdf.format((Date) o);
            s = S.addDoubleQuot(maxLength > 0 ? S.left(s, maxLength) : s);
        } else if (o instanceof Collection || (o != null && o.getClass().isArray())) {
            s = "[]";
        } else if (Map.class.getName().equals(c) || HashMap.class.getName().equals(c)) {
            s = "{}";
        } else {
            s = S.addDoubleQuot("");
        }
        return s;
    }

    /**
     * 一个class是否实现了某个接口
     *
     * @param c
     * @param szInterface
     * @return
     */
    public static boolean isInterface(Class c, String szInterface) {
        Class[] face = c.getInterfaces();
        for (int i = 0, j = face.length; i < j; i++) {
            if (face[i].getName().equals(szInterface)) {
                return true;
            } else {
                Class[] face1 = face[i].getInterfaces();
                for (int x = 0; x < face1.length; x++) {
                    if (face1[x].getName().equals(szInterface)) {
                        return true;
                    } else if (isInterface(face1[x], szInterface)) {
                        return true;
                    }
                }
            }
        }
        if (null != c.getSuperclass()) {
            return isInterface(c.getSuperclass(), szInterface);
        }
        return false;
    }

    /**
     * 得到一个类中所有可用的Field的字符串List
     *
     * @param <T>
     * @param o
     * @return
     */
    public static <T> List<String> getFieldNameList(T o) {
        List<String> list = new ArrayList<String>();
        try {
            List<Field> flist = S.getAllFieldsIncludeSuper(((T) o).getClass());
            for (Field field : flist) {
                list.add(field.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 向现有的json格式字串添加一个名称为key值为value的 key-value 对
     *
     * @param jsonString
     * @param key
     * @param jsonValue , 已经是json格式, 不要再添加引号了
     * @return
     */
    public static String push(String jsonString, String key, String jsonValue) {
        if (S.isEmpty(jsonString)
                || S.isEmpty(key)
                || S.isEmpty(jsonValue)
                || !jsonString.trim().endsWith("}")) {
            return jsonString;
        }
        jsonString = jsonString.trim();
        jsonString = jsonString.substring(0, jsonString.length() - 1)
                + (jsonString.indexOf(":") > 0 ? ", " : "")
                + S.addDoubleQuot(key) + ": "
                + jsonValue
                + "}";
        return jsonString;
    }

    public static void main(String[] args) {
        System.out.println(JSONUtil.toJSON(new Date()));
    }
}



S.java
package utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class S {

    public static DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static DateFormat sdfAli = new SimpleDateFormat("yyyy.MM.dd HH:mm");
    public static DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public static DateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
    public static DecimalFormat df1 = new DecimalFormat("0.0");
    public static DecimalFormat df2 = new DecimalFormat("0.00");
    public static DecimalFormat df3 = new DecimalFormat("0.000");
    public static DecimalFormat df4 = new DecimalFormat("0.0000");
    public static DecimalFormat df1x = new DecimalFormat("0.#");
    public static DecimalFormat df2x = new DecimalFormat("0.##");
    public static DecimalFormat df3x = new DecimalFormat("0.###");
    public static DecimalFormat df4x = new DecimalFormat("0.####");
    public static final int decode = 1;// 标志是否用 java.net.URLDecoder.decode 解码

    public static String xstring(String x) {
        return (null == x || x.trim().length() == 0) ? null : x.trim();
    }

    public static String xstring(String x, int decode) {
        return xstring(x, "", decode);
    }

    public static String xstring(String x, String defalutValue) {
        return xstring(x) == null ? defalutValue : xstring(x);
    }

    public static String xstring(String x, String defalutValue, int decode) {
        try {
            x = java.net.URLDecoder.decode(S.xstring(x, defalutValue), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return x;
    }

    public static int xint(String x) {
        return (int) (xfloat(x));
    }

    public static int xint(String x, int defalutValue) {
        return xstring(x, "").replaceAll("[^0-9-.]", "").trim().length() == 0 ? defalutValue : xint(x);
    }

    public static double xdouble(String x, double defalutValue) {
        return Double.parseDouble(xstring(xstring(x, "").replaceAll("[^0-9-.]", ""), "0"));
    }

    public static double xdouble(String x) {
        return xdouble(x, 0d);
    }

    public static long xlong(String x, long defalutValue) {
        return xstring(x, "").replaceAll("[^0-9-.]", "").trim().length() == 0 ? defalutValue : ((long) xdouble(x));
    }

    public static long xlong(String x) {
        return xlong(x, 0l);
    }

    public static float xfloat(String x) {

        return Float.parseFloat(xstring(xstring(x, "").replaceAll("[^0-9-.]", ""), "0"));
    }

    public static float xfloat(String x, float defalutValue) {
        return xstring(x, "").replaceAll("[^0-9-.]", "").trim().length() == 0f ? defalutValue : xfloat(x);
    }

    public static String clean(String x) {
        return S.xstring(x, "").replaceAll("[^0-9a-zA-Z-]", "");
    }

    public static String inSql(String x) {
        return S.xstring(x, "").replace("'", "''");
    }

    public static String inDoubleQuot(String x) {
        return S.xstring(x, "").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n");
    }

    public static String addDoubleQuot(String x) {
        return "\"" + inDoubleQuot(x) + "\"";
    }

    public static String inSingleQuot(String x) {
        return S.xstring(x, "").replace("'", "\\'").replace("\r", "\\r").replace("\n", "\\n");
    }

    public static String addSingleQuot(String x) {
        return "'" + inSingleQuot(x) + "'";
    }

    public static String riqi(Date date) {
        if (date == null) {
            return "";
        }
        return sdf.format(date);
    }

    public static String riqi() {
        return sdf.format(new Date());
    }

    public static String riqiAli(Date date) {
        return sdfAli.format(date);
    }

    public static String riqi2(Date date) {
        if (date == null) {
            return "";
        }
        return sdf2.format(date);
    }

    public static String riqi2() {
        return sdf2.format(new Date());
    }

    public static String riqi3(Date date) {
        if (date == null) {
            return "";
        }
        return sdf3.format(date);
    }

    public static String riqi3() {
        return sdf3.format(new Date());
    }

    public static String riqi(java.sql.Date date) {
        return sdf.format(new java.util.Date(date.getTime()));
    }

    public static boolean isEmpty(String x) {
        return x == null || x.trim().equals("") || x.trim().equals("null");
    }

    public static String left(String x, int num) {
        x = S.xstring(x, "");
        return x.length() < num ? x : x.substring(0, num);
    }

    public static String right(String x, int num) {
        x = S.xstring(x, "");
        return x.length() <= num ? x : x.substring(x.length() - num);
    }

    public static String now() {
        return sdf.format(System.currentTimeMillis());
    }

    @Deprecated
    public static boolean isInList(String s, List<String> list) {
        for (String c : list) {
            if ((c == null && s == null) || (s != null && s.equals(c))) {
                return true;
            }
        }
        return false;
    }

    @Deprecated
    public static boolean isInArray(String s, String[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if ((arr[i] == null && s == null) || (s != null && s.equals(arr[i]))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 整数a是否在list中
     *
     * @param a
     * @param list
     * @return
     */
    public static boolean inList(int a, List<Integer> list) {
        for (Integer i : list) {
            if (a == i.intValue()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 整数a是否在数组中
     *
     * @param a
     * @param list
     * @return
     */
    public static boolean inArray(int a, int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (a == arr[i]) {
                return true;
            }
        }
        return false;
    }

    public static boolean inArray(String s, String[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if ((arr[i] == null && s == null) || (s != null && s.equals(arr[i]))) {
                return true;
            }
        }
        return false;
    }

    @Deprecated
    public static <T> String toJSON(T o) {
        return JSONUtil.toJSON(o, 100, false, null, 0);
    }

    /**
     * 将前n个字母大写
     *
     * @param s
     * @param count
     * @return
     */
    public static String upper(String s, int n) {
        if (s == null) {
            return null;
        } else if (s.length() <= n) {
            return s.toUpperCase();
        } else {
            return s.substring(0, n).toUpperCase() + s.substring(n);
        }
    }

    public static String javaUpper(String s) {
        if (s == null) {
            return null;
        } else if (s.length() == 1) {
            return s.toUpperCase();
        } else {
            if (s.substring(1, 2).replaceAll("[A-Z]", "").length() == 0) {
                return s;
            } else {
                return s.substring(0, 1).toUpperCase() + s.substring(1);
            }
        }
    }

    /**
     * 将一个对象中所有String类型decode
     *
     * @param <T>
     * @param o
     * @param encoding
     */
    public static <T> void decode(T o, String encoding) {
        if (o != null) {
            try {
                Field[] fields = o.getClass().getDeclaredFields();
                Method[] methods = o.getClass().getMethods();
                String c = "";
                String get = "";
                String set = "";
                int geti = -1;
                int seti = -1;
                for (Field f : fields) {
                    c = f.getType().getName();
                    if (String.class.getName().equals(c)) {
                        geti = -1;
                        seti = -1;
                        for (int idx = 0; idx < methods.length; idx++) {
                            set = S.markMethodString(f, "set");
                            get = S.markMethodString(f, "get");

                            if (methods[idx].getName().equals(set)) {
                                seti = idx;
                            } else if (methods[idx].getName().equals(get)) {
                                geti = idx;
                            }
                            if (seti > -1 && geti > -1) {
                                String value = methods[geti].invoke(o) == null ? null : ((String) methods[geti].invoke(o));
                                if (value != null) {
                                    value = java.net.URLDecoder.decode(value, encoding);
                                    //value = new String(value.getBytes("iso-8859-1"), "utf-8");
                                    methods[seti].invoke(o, value);
                                }
                                break;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String markMethodString(Field f, String type) {
        String s = "";
        if ("get".equals(type)) {
            s = (f.getType().getName().equals(boolean.class.getName()) ? "is" : "get") + javaUpper(f.getName());
        } else if ("set".equals(type)) {
            s = "set" + javaUpper(f.getName());
        }
        return s;
    }

    /**
     * 将一个字符串decode
     *
     * @param s
     * @param encoding
     * @return
     */
    public static String decode(String s, String encoding) {
        try {
            s = s == null ? null : java.net.URLDecoder.decode(s, encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 某个类中是否含有某个set方法
     *
     * @param <T>
     * @param o
     * @param field
     * @return
     */
    public static boolean hasMethod(Class c, String method, Class... parameterTypes) {
        try {
            c.getMethod(method, parameterTypes);
            return true;
        } catch (Exception e) {
            //S.p("---S.hasMethod: " + e.toString());
            return false;
        }
    }

    /**
     * 将A转化为B
     *
     * @param <A>
     * @param <B>
     * @param a
     * @param b
     */
    public static <A, B> B convert(A a, B b) {
        try {
            List<Field> flist = S.getAllFieldsIncludeSuper(b.getClass());
            String get = "";
            String set = "";
            Object o = null;
            for (Field f : flist) {
                get = S.markMethodString(f, "get");
                set = S.markMethodString(f, "set");
                if (S.hasMethod(a.getClass(), get) && S.hasMethod(b.getClass(), set, f.getType())) {
                    o = a.getClass().getMethod(get).invoke(a);
                    b.getClass().getMethod(set, f.getType()).invoke(b, o);
                }
            }
        } catch (Exception e) {
            S.p("---S.convert(Cast " + a.getClass().getName() + " to " + b.getClass().getName() + "): " + e.toString());
        }
        return b;
    }

    public static List<Field> getAllFields(Class c) {
        List<Field> flist = new ArrayList<Field>();
        flist.addAll(Arrays.asList(c.getDeclaredFields()));
        return flist;
    }

    public static List<Field> getAllFieldsIncludeSuper(Class c) {
        List<Field> flist = new ArrayList<Field>();
        flist.addAll(Arrays.asList(c.getDeclaredFields()));
        flist.addAll(S.getSuperClassFields(c));
        return flist;
    }

    public static List<Field> getSuperClassFields(Class c) {
        List<Field> rslist = new ArrayList<Field>();
        c = c.getSuperclass();
        if (c != null && c.getName() != null && !c.getName().equals(Object.class.getName())) {
            if (c.getDeclaredFields().length > 0) {
                rslist.addAll(Arrays.asList(c.getDeclaredFields()));
            }
            List<Field> flist = getSuperClassFields(c);
            rslist.addAll(flist);
        }
        return rslist;
    }

    public static void p(String s) {
        System.out.println(s);
    }

    public static void p() {
        System.out.println("");
    }

    public static void main(String[] args) {
    }
}

0
2
分享到:
评论
2 楼 sanshizi 2012-10-25  
Chris_bing 写道
有Jackson,Gson,json-smart那么多类库,干嘛要自己写啊

呵呵, 目前还处在学习阶段, 见笑见笑
1 楼 Chris_bing 2012-10-21  
有Jackson,Gson,json-smart那么多类库,干嘛要自己写啊

相关推荐

Global site tag (gtag.js) - Google Analytics