Java中的JSON序列化和反序列化 和Vo的转换

Java中的JSON序列化和反序列化例子:

Java代码   收藏代码
  1.      /** 
  2.  * 由字符串反序列化成实体类  针对的是一个实体,此实体中的属性不包括自定义的类型,如Teacher类型,或者List类型  
  3.  * @param source 传入json中的字符串 
  4.  * @param beanClass 实体类的类型 
  5.  * @return 实体类 
  6.  */  
  7. public static Object getObjFromJsonArrStr(String source,Class beanClass)  
  8. {  
  9.     JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(source);  
  10.     return  JSONObject.toBean(jsonObject,beanClass);          
  11. }  
  12. /** 
  13.  * 由字符串反序列化成实体类  针对的是一个实体,此实体中的属性包括自定义的类型,如Teacher类型,或者List类型 
  14.  * @param jsonArrStr 
  15.  * @param clazz 
  16.  * @param classMap 
  17.  * @return 
  18.  */  
  19. public static Object getObjFromJsonArrStr(String jsonArrStr, Class clazz, Map classMap)   
  20. {    
  21.     JSONObject jsonObj = JSONObject.fromObject(jsonArrStr);    
  22.                return JSONObject.toBean(jsonObj, clazz, classMap);              
  23. }  
  24.   
  25.   
  26. /** 
  27.  * 将string转换成listBean 
  28.  * @param jsonArrStr 需要反序列化的字符串 
  29.  * @param clazz 被反序列化之后的类 
  30.  * @return 实体list 
  31.  */  
  32. @SuppressWarnings("unchecked")  
  33. public static List getListFromJsonArrStr(String jsonArrStr, Class clazz) {    
  34.        JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);    
  35.        List list = new ArrayList();    
  36.        for (int i = 0; i < jsonArr.size(); i++)   
  37.        {    
  38.            list.add(JSONObject.toBean(jsonArr.getJSONObject(i), clazz));    
  39.        }    
  40.        return list;    
  41.    }   
  42.   
  43. /** 
  44.  * 将string转换成listBean 属性中包含实体类等 如List 而Student中含有属性List 
  45.  * @param jsonArrStr 需要反序列化的字符串 
  46.  * @param clazz 反序列化后的类 
  47.  * @param classMap 将属性中包含的如Teacher加入到一个Map中,格式如map.put("teacher",Teacher.class) 
  48.  * @return 反序列化后的字符串 
  49.  * 使用示例: 
  50.     Map classMap = new HashMap(); 
  51.     //必须要对Parent进行初始化 否则不识别 
  52.     Teacher p = new Teacher(); 
  53.     classMap.put("teacher", p.getClass()); 
  54.     List mlist = JSONTransfer.getListFromJsonArrStr(resultStr, Student.class, classMap); 
  55.  */  
  56. @SuppressWarnings("unchecked")  
  57. public static List getListFromJsonArrStr(String jsonArrStr, Class clazz, Map classMap)   
  58. {    
  59.       JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);    
  60.       List list = new ArrayList();    
  61.       for (int i = 0; i < jsonArr.size(); i++)   
  62.       {              
  63.           list.add(JSONObject.toBean(jsonArr.getJSONObject(i), clazz, classMap));    
  64.       }    
  65.       return list;    
  66. }  
  67.       
  68. /** 
  69.  * 序列化操作,无论是单个的对象,还是list,抑或是list中的属性仍包含list,都可以直接序列化成String类型 
  70.  * @param obj 需要被序列化的对象 
  71.  * @return 序列化之后的字符串 
  72.  */  
  73. @SuppressWarnings("unchecked")  
  74. public static String getJsonArrStrFromList(Object obj)   
  75. {   
  76.     //返回結果  
  77.     String jsonStr = null;    
  78.     //判空  
  79.        if (obj == null) {    
  80.            return "{}";    
  81.        }    
  82.        //Json配置        
  83.        JsonConfig jsonCfg = new JsonConfig();    
  84.    
  85.        //注册日期处理器    
  86.        jsonCfg.registerJsonValueProcessor(java.util.Date.class,    
  87.                new JsonDateValueProcessor(SystemConstants.DateFormat));    
  88.          
  89.        //判断是否是list  
  90.        if (obj instanceof Collection || obj instanceof Object[]) {    
  91.            jsonStr = JSONArray.fromObject(obj, jsonCfg).toString();    
  92.        } else {    
  93.            jsonStr = JSONObject.fromObject(obj, jsonCfg).toString();    
  94.        }        
  95.        return jsonStr;   
  96.    }   







package cn.fiyo.base.util;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
 
import cn.easecom.platform.module.basic.web.user.UserContext;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
 
public class JsonUtils {
     private static final Log log = LogFactory.getLog(JsonUtils. class );
     
     public JsonUtils() {
         
     }
     
     /**
      * 向客户端输出JSON
      */
     public static void outputJson(HttpServletResponse response, JSONObject json)
             throws Exception {
         response.setCharacterEncoding( "UTF-8" );
         PrintWriter out = response.getWriter();
         out.write(json.toString());
         out.flush();
     }
 
     /**
      * 从一个JSON 对象字符格式中得到一个java对象
      *
      */
 
     public static Object toBean(String jsonString, Class beanClass) {
         JSONObject jsonObject = JSONObject.fromObject(jsonString);
         Object object = JSONObject.toBean(jsonObject, beanClass);
         return object;
     }
     
     public static Object toBean(String jsonString, Class beanClass,Map map) {
         JSONObject jsonObject = JSONObject.fromObject(jsonString);
         Object object = JSONObject.toBean(jsonObject, beanClass,map);
         return object;
     }
 
     /**
      * 从json对象集合表达式中得到一个java对象列表
      * @param jsonString:数组字符串[{key1:value1,key2:value2},{bean2},{bean3},...]
      * @param pojoClass
      * @return
      */
     public static List toList(String jsonString, Class beanClass) {
         JSONArray jsonArray = JSONArray.fromObject(jsonString);
         List list = new ArrayList();
         for ( int i = 0 ; i < jsonArray.size(); i++) {
             JSONObject jsonObject = jsonArray.getJSONObject(i);
             Object object = JSONObject.toBean(jsonObject, beanClass);
             list.add(object);
         }
         return list;
     }
     public static List toList(String jsonString, Class beanClass,Map map) {
         JSONArray jsonArray = JSONArray.fromObject(jsonString);
         List list = new ArrayList();
         for ( int i = 0 ; i < jsonArray.size(); i++) {
             JSONObject jsonObject = jsonArray.getJSONObject(i);
             Object object = JSONObject.toBean(jsonObject, beanClass,map);
             list.add(object);
         }
         return list;
     }
 
     /**
      * 从json字符串中获取一个map,该map支持嵌套功能
      * @param jsonString
      * @return
      */
     public static Map toMap(String jsonString) {
         JSONObject jsonObject = JSONObject.fromObject(jsonString);
         Iterator it = jsonObject.keys();
         Map map = new HashMap();
         while (it.hasNext()) {
             String key = (String) it.next();
             Object value = jsonObject.get(key);
             map.put(key, value);
         }
         return map;
     }
     
     /**
      * 从json数组中得到相应java数组
      * @param jsonString
      * @return
      */
     public static Object[] toObjectArray(String jsonString) {
         JSONArray jsonArray = JSONArray.fromObject(jsonString);
         return jsonArray.toArray();
     }
 
     /**
      * 从json解析出java字符串数组
      * @param jsonString
      * @return
      */
     public static String[] toStringArray(String jsonString) {
         JSONArray jsonArray = JSONArray.fromObject(jsonString);
         String[] stringArray = new String[jsonArray.size()];
         for ( int i = 0 ; i < jsonArray.size(); i++) {
             stringArray[i] = jsonArray.getString(i);
         }
         return stringArray;
     }
 
     /**
      * 从json解析出javaLong型对象数组
      * @param jsonString
      * @return
      */
     public static Long[] toLongArray(String jsonString) {
 
         JSONArray jsonArray = JSONArray.fromObject(jsonString);
         Long[] longArray = new Long[jsonArray.size()];
         for ( int i = 0 ; i < jsonArray.size(); i++) {
             longArray[i] = jsonArray.getLong(i);
         }
         return longArray;
     }
 
     /**
      * 从json解析出java Integer型对象数组
      * @param jsonString:[1,2,3,4]
      * @return
      */
     public static Integer[] toIntegerArray(String jsonString) {
         JSONArray jsonArray = JSONArray.fromObject(jsonString);
         Integer[] integerArray = new Integer[jsonArray.size()];
         for ( int i = 0 ; i < jsonArray.size(); i++) {
             integerArray[i] = jsonArray.getInt(i);
         }
         return integerArray;
     }
 
     
     /**
      * 从json中解析出java Double型对象数组
      * @param jsonString
      * @return
      */
     public static Double[] toDoubleArray(String jsonString) {
         JSONArray jsonArray = JSONArray.fromObject(jsonString);
         Double[] doubleArray = new Double[jsonArray.size()];
         for ( int i = 0 ; i < jsonArray.size(); i++) {
             doubleArray[i] = jsonArray.getDouble(i);
         }
         return doubleArray;
     }
 
     /**
      * 将java对象转换成json字符串
      * @param javaObj
      * @return
      */
     public static String toJsonString(Object object) {
         JSONObject json = JSONObject.fromObject(object);
         return json.toString();
     }
 
     /*
      * 将java对象转化为json数组字符串
      * [{"name":"name1","id":"id1"},{"name":"name2","id":"id2"}]
      */
     public static String toJsonArrayString(List list) {
         JSONArray jsonArray = JSONArray.fromObject(list);
         return jsonArray.toString();
     }
 
     private String dateFormat = "yyyy-MM-dd";
 
     public void setDateFormat(String dateFormat){
         this.dateFormat = dateFormat;
     }
 
     /**
      * 格式化日期字符串
      */
     public void initBinder(HttpServletRequest request,ServletRequestDataBinder binder){
         SimpleDateFormat dateFormat = new SimpleDateFormat(this.dateFormat);
         dateFormat.setLenient(false);
         binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
         binder.registerCustomEditor(String.class,new StringTrimmerEditor(false));
     }
    
     @SuppressWarnings("unchecked")
     public static void outputJsonResponse(HttpServletResponse response,boolean result){
         JSONObject json = new JSONObject();
         json.put("result", result);
         String content=json.toString();
         flushResponse(response,content);
     }
     /*
      * {"result":true,"msg":"abc"}
      */
     @SuppressWarnings("unchecked")
     public static void outputJsonResponse(HttpServletResponse response,boolean result,String message){
         JSONObject json = new JSONObject();
         json.put("result", result);
         json.put("message", message);
         String content=json.toString();
         flushResponse(response,content);
     }
     @SuppressWarnings("unchecked")
     public static void outputJsonResponse(HttpServletResponse response,boolean result,String message,String userData){
         JSONObject json = new JSONObject();
         json.put("result", result);
         json.put("message", message);
         json.put("userData", userData);
         String content=json.toString();
         flushResponse(response,content);
     }
     /*
      * {"result":true,"data":{"key1":"value1","key2":"value2"}}
      */
     @SuppressWarnings("unchecked")
     public static void outputJsonResponse(HttpServletResponse response,boolean result,String message,Map userData){
         JSONObject json = new JSONObject();
         json.put("result", result);
         json.put("message", message);
         if(userData!=null && userData.size()>0)
             json.put("userData", userData);
         String content=json.toString();
         flushResponse(response,content);
     }
     
     /*
      * 输出json数据
      * 输出格式为:{result:true,data:[{"name":"name1","id":"id1"},{"name":"name2","id":"id2"}]}
      */
     public static void outputJsonResponse(HttpServletResponse response,boolean result,List list) {
         JSONObject json = new JSONObject();
         json.put("result", result);
         if (list!=null && list.size()>0){
             JSONArray jsonArray = JSONArray.fromObject(list);
             json.put("data", jsonArray);
         }
         String content=json.toString();
         flushResponse(response,content);
     }
        
     /*
      * 输出ext列表的json数据
      * 输出格式为:{totalProperty:12,root:[{"name":"name1","id":"id1"},{"name":"name2","id":"id2"}]}
      */
     public static void outputJsonDataForExt(HttpServletResponse response,int totalProperty,List list) {
         JSONObject json = new JSONObject();
         json.put("totalProperty", totalProperty);
         if (list!=null && list.size()>0){
             JSONArray jsonArray = JSONArray.fromObject(list);
             json.put("root", jsonArray);
         }
         String content=json.toString();
         flushResponse(response,content);
     }
     /**
      * Method to flush a String as response.
      * @param response
      * @param responseContent
      * @throws IOException
      */
     public static void flushResponse(HttpServletResponse response,String responseContent){
         response.setCharacterEncoding("UTF-8");
         try {
             PrintWriter writer = response.getWriter();
             writer.write(responseContent);
             writer.flush();
             writer.close();
         } catch (IOException e) {
             log.error(e.getMessage());
         }
     }
     /**
      * @param response
      */
     public static void outputXML(HttpServletResponse response, String xml) throws Exception {
         response.setContentType("text/xml; charset=UTF-8");
         PrintWriter out = response.getWriter();
         out.write(xml);
         out.flush();
     }
     
     /*
      * 属性拷贝
      */
     public void copyProperties(Object dest, Object orig) {
         try {
             BeanUtils.copyProperties(dest, orig);
         } catch (Exception ex) {
             log.error( "Copy property error: " + ex.toString());
         }
     }
}

你可能感兴趣的:(Java中的JSON序列化和反序列化 和Vo的转换)