注册 登录  
 加关注
查看详情
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

流星永恒的博客

JSF,Facelets,Rich(Prime)Faces,和java的笔记

 
 
 

日志

 
 

JSON and bean covert each other(json和javabean互相转换)  

2010-02-26 22:19:43|  分类: java |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

        自己写的简单对象和json字符串这间的转换类。因为在做一个仿web service的需求,就写了这么个实用类,有错误或者得改进的地方,请留言告知。

      注意:简单对象指一个对象中不包含其他自己定义对象。

     其中setter getter必须是set或者get或者is后的第一个字符是字母或'$',其他的无法解析

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.util;

import com.test.User;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.richfaces.json.JSONArray;
import org.richfaces.json.JSONException;
import org.richfaces.json.JSONObject;
import org.richfaces.json.JSONTokener;

/**
 *
 * @author Daniel
 */
public class JSONUtils {

    public static void main(String args[]) throws JSONException {
        List<User> list = new ArrayList<User>();
        User u = new User("\"yyq", "DV", 25, new Timestamp(new Date().getTime()), true);
        User u1 = new User("yyq1", "DV", 24, new Timestamp(new Date().getTime()), false);
        User u2 = new User("yyq2", "DV", 23, new Timestamp(new Date().getTime()), true);
        User u3 = new User("yyq3", "DV", 22, new Timestamp(new Date().getTime()), true);
        list.add(u);
        list.add(u1);
        list.add(u2);
        list.add(u3);
        String jsonArr = JSONUtils.beanList2JsonArray(list);
           System.out.println(jsonArr);
        try {
            JSONArray ja = new JSONArray(new JSONTokener(jsonArr));
            System.out.println(ja.length());
            List<User> list1 = JSONUtils.jsonArray2BeanList(User.class, jsonArr);
            for (User user : list1) {
                System.out.println(user.is$Married());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * convert simple bean(not reference other beans) to json string<br/>
     * complex object can be processed as serials simple bean
     * @param <T>
     * @param clazz
     * @param t
     * @return
     */
    public static <T> String bean2Json(T t) {
        Method[] methods = t.getClass().getDeclaredMethods();
        String propertyName[] = new String[methods.length];
        int capacity = 0;
        for (int i = 0; i < methods.length; i++) {
            String name = methods[i].getName();
            if (name.matches("(?:is|get)[A-Z$]\\w+")) {//is setter
                StringBuilder sb = new StringBuilder(name);
                int start;
                if (sb.charAt(1) == 's') {
                    start = 2;
                } else {
                    start = 3;
                }
                sb.delete(0, start);
                if (Character.isLetter(sb.charAt(0))) {
                    sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
                }
                propertyName[capacity] = sb.toString();
                capacity++;
            }
        }

        StringBuilder builder = new StringBuilder();
        builder.append("{");
        for (int i = 0; i < capacity; i++) {
            try {
                String value = BeanUtils.getProperty(t, propertyName[i]);
                builder.append(propertyName[i]);
                builder.append("=\"");
                builder.append(string2Json(value));// process some special character
                if (i < capacity - 1) {
                    builder.append("\", ");
                } else {
                    builder.append("\"");
                }
            } catch (IllegalAccessException ex) {
                //TODO
            } catch (InvocationTargetException ex) {
                //TODO
            } catch (NoSuchMethodException ex) {
                //TODO
            }
        }
        builder.append("}");
        return builder.toString();
    }

    /**
     * conver json array to java bean list
     *
     * @param <T>
     * @param clazz
     * @param jsonarray
     * @return
     * @throws JSONException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws InvocationTargetException
     * @throws IntrospectionException
     * @throws IllegalArgumentException
     * @throws ClassNotFoundException
     */
    public static <T> List<T> jsonArray2BeanList(Class<T> clazz, String jsonarray) throws JSONException, InstantiationException, IllegalAccessException, IllegalArgumentException, IntrospectionException, InvocationTargetException, ClassNotFoundException {
        JSONArray ja = new JSONArray(new JSONTokener(jsonarray));
        List<T> list = new ArrayList<T>();
        Method[] methods = clazz.getDeclaredMethods();
        int len = ja.length();
        for (int i = 0; i < len; i++) {
            T t = (T) clazz.newInstance();
            JSONObject jo = ja.getJSONObject(i);
            for (int j = 0; j < methods.length; j++) {
                String val = null;
                Method method = methods[j];
                if (method.getName().matches("set[A-Z$]\\w+")) {
                    try {
                        String property = propertyName(methods[j].getName());
                        if (null == property || ("".equals(property))) {
                            continue;
                        }
                        val = jo.getString(property);
                        BeanUtils.setProperty(t, property, val);
                    } catch (Exception e) {
                        continue;
                    }
                }
            }
            list.add(t);
        }
        return list;
    }

    public static String propertyName(String setMetherName) {
        StringBuilder builder = new StringBuilder(setMetherName);
        builder.delete(0, 3);
        char c = builder.charAt(0);
        builder.setCharAt(0, Character.toLowerCase(c));
        return builder.toString();
    }

    public static <T> String beanList2JsonArray(List<T> list) {
        if (null == list) {
            return null;
        }
        if (list.isEmpty()) {
            return "[]";
        }
        int len = list.size();
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        for (int i = 0; i < len; i++) {
            T t = list.get(i);
            builder.append(bean2Json(t));
            if (i < len - 1) {
                builder.append(", ");
            }
        }
        builder.append("]");
        return builder.toString();
    }


    public static String string2Json(String s) {
      if(null==s||"".equals(s))return s;
      StringBuilder sb = new StringBuilder();
    for (int i=0; i<s.length(); i++) {
        char c = s.charAt(i);
        switch (c) {
        case '\"':
            sb.append("\\\"");
            break;
        case '\\':
            sb.append("\\\\");
            break;
        case '/':
            sb.append("\\/");
            break;
        case '\b':
            sb.append("\\b");
            break;
        case '\f':
            sb.append("\\f");
            break;
        case '\n':
            sb.append("\\n");
            break;
        case '\r':
            sb.append("\\r");
            break;
        case '\t':
            sb.append("\\t");
            break;
        default:
            sb.append(c);
        }
    }
        return sb.toString();
}
}

 

工具类:http://yyq2007aa.blog.163.com/blog/static/4418160920102101439144/

  评论这张
 
阅读(673)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018