json数据与JAVA数据的转换

本文介绍了一款自编的工具类JsonUtil,用于处理页面提交的JSON数据格式,并将其转化为Java对象。文章详细展示了如何处理日期格式问题,并提供了完整的Java代码实现。

自己编写了一个工具类,处理页面提交json格式数据到后台,再进行处理成JAVA对象数据

1、DTO:Data Transfer Object,数据传送对象

2、对于日期格式的问题,也已经处理

3、json-lib-2.2.2-jdk13.jar (2.1在日期数组 json->java有问题)

 

工具类JsonUtil代码如下:

 

Java代码  收藏代码
  1. public class JsonUtil {  
  2.   
  3.     /**页面传至后台时,json数据在request的参数名称*/  
  4.     public final static String JSON_ATTRIBUTE = "json";  
  5.     public final static String JSON_ATTRIBUTE1 = "json1";  
  6.     public final static String JSON_ATTRIBUTE2 = "json2";  
  7.     public final static String JSON_ATTRIBUTE3 = "json3";  
  8.     public final static String JSON_ATTRIBUTE4 = "json4";  
  9.       
  10.     /** 
  11.      * 从一个JSON 对象字符格式中得到一个java对象,形如: 
  12.      * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}} 
  13.      * @param object 
  14.      * @param clazz 
  15.      * @return 
  16.      */  
  17.     public static Object getDTO(String jsonString, Class clazz){  
  18.         JSONObject jsonObject = null;  
  19.         try{  
  20.             setDataFormat2JAVA();   
  21.             jsonObject = JSONObject.fromObject(jsonString);  
  22.         }catch(Exception e){  
  23.             e.printStackTrace();  
  24.         }  
  25.         return JSONObject.toBean(jsonObject, clazz);  
  26.     }  
  27.       
  28.     /** 
  29.      * 从一个JSON 对象字符格式中得到一个java对象,其中beansList是一类的集合,形如: 
  30.      * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}, 
  31.      * beansList:[{}, {}, ...]} 
  32.      * @param jsonString 
  33.      * @param clazz 
  34.      * @param map 集合属性的类型 (key : 集合属性名, value : 集合属性类型class) eg: ("beansList" : Bean.class) 
  35.      * @return 
  36.      */  
  37.     public static Object getDTO(String jsonString, Class clazz, Map map){  
  38.         JSONObject jsonObject = null;  
  39.         try{  
  40.             setDataFormat2JAVA();   
  41.             jsonObject = JSONObject.fromObject(jsonString);  
  42.         }catch(Exception e){  
  43.             e.printStackTrace();  
  44.         }  
  45.         return JSONObject.toBean(jsonObject, clazz, map);  
  46.     }  
  47.       
  48.     /** 
  49.      * 从一个JSON数组得到一个java对象数组,形如: 
  50.      * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...] 
  51.      * @param object 
  52.      * @param clazz 
  53.      * @return 
  54.      */  
  55.     public static Object[] getDTOArray(String jsonString, Class clazz){  
  56.         setDataFormat2JAVA();  
  57.         JSONArray array = JSONArray.fromObject(jsonString);  
  58.         Object[] obj = new Object[array.size()];  
  59.         for(int i = 0; i < array.size(); i++){  
  60.             JSONObject jsonObject = array.getJSONObject(i);  
  61.             obj[i] = JSONObject.toBean(jsonObject, clazz);  
  62.         }  
  63.         return obj;  
  64.     }  
  65.       
  66.     /** 
  67.      * 从一个JSON数组得到一个java对象数组,形如: 
  68.      * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...] 
  69.      * @param object 
  70.      * @param clazz 
  71.      * @param map 
  72.      * @return 
  73.      */  
  74.     public static Object[] getDTOArray(String jsonString, Class clazz, Map map){  
  75.         setDataFormat2JAVA();  
  76.         JSONArray array = JSONArray.fromObject(jsonString);  
  77.         Object[] obj = new Object[array.size()];  
  78.         for(int i = 0; i < array.size(); i++){  
  79.             JSONObject jsonObject = array.getJSONObject(i);  
  80.             obj[i] = JSONObject.toBean(jsonObject, clazz, map);  
  81.         }  
  82.         return obj;  
  83.     }  
  84.       
  85.     /** 
  86.      * 从一个JSON数组得到一个java对象集合 
  87.      * @param object 
  88.      * @param clazz 
  89.      * @return 
  90.      */  
  91.     public static List getDTOList(String jsonString, Class clazz){  
  92.         setDataFormat2JAVA();  
  93.         JSONArray array = JSONArray.fromObject(jsonString);  
  94.         List list = new ArrayList();  
  95.         for(Iterator iter = array.iterator(); iter.hasNext();){  
  96.             JSONObject jsonObject = (JSONObject)iter.next();  
  97.             list.add(JSONObject.toBean(jsonObject, clazz));  
  98.         }  
  99.         return list;  
  100.     }  
  101.       
  102.     /** 
  103.      * 从一个JSON数组得到一个java对象集合,其中对象中包含有集合属性 
  104.      * @param object 
  105.      * @param clazz 
  106.      * @param map 集合属性的类型 
  107.      * @return 
  108.      */  
  109.     public static List getDTOList(String jsonString, Class clazz, Map map){  
  110.         setDataFormat2JAVA();  
  111.         JSONArray array = JSONArray.fromObject(jsonString);  
  112.         List list = new ArrayList();  
  113.         for(Iterator iter = array.iterator(); iter.hasNext();){  
  114.             JSONObject jsonObject = (JSONObject)iter.next();  
  115.             list.add(JSONObject.toBean(jsonObject, clazz, map));  
  116.         }  
  117.         return list;  
  118.     }  
  119.       
  120.     /** 
  121.      * 从json HASH表达式中获取一个map,该map支持嵌套功能 
  122.      * 形如:{"id" : "johncon", "name" : "小强"} 
  123.      * 注意commons-collections版本,必须包含org.apache.commons.collections.map.MultiKeyMap 
  124.      * @param object 
  125.      * @return 
  126.      */  
  127.     public static Map getMapFromJson(String jsonString) {  
  128.         setDataFormat2JAVA();  
  129.         JSONObject jsonObject = JSONObject.fromObject(jsonString);  
  130.         Map map = new HashMap();  
  131.         for(Iterator iter = jsonObject.keys(); iter.hasNext();){  
  132.             String key = (String)iter.next();  
  133.             map.put(key, jsonObject.get(key));  
  134.         }  
  135.         return map;  
  136.     }  
  137.       
  138.     /** 
  139.      * 从json数组中得到相应java数组 
  140.      * json形如:["123", "456"] 
  141.      * @param jsonString 
  142.      * @return 
  143.      */  
  144.     public static Object[] getObjectArrayFromJson(String jsonString) {  
  145.         JSONArray jsonArray = JSONArray.fromObject(jsonString);  
  146.         return jsonArray.toArray();  
  147.     }  
  148.   
  149.   
  150.     /** 
  151.      * 把数据对象转换成json字符串 
  152.      * DTO对象形如:{"id" : idValue, "name" : nameValue, ...} 
  153.      * 数组对象形如:[{}, {}, {}, ...] 
  154.      * map对象形如:{key1 : {"id" : idValue, "name" : nameValue, ...}, key2 : {}, ...} 
  155.      * @param object 
  156.      * @return 
  157.      */  
  158.     public static String getJSONString(Object object) throws Exception{  
  159.         String jsonString = null;  
  160.         //日期值处理器  
  161.         JsonConfig jsonConfig = new JsonConfig();  
  162.         jsonConfig.registerJsonValueProcessor(java.util.Date.classnew JsonDateValueProcessor());  
  163.         if(object != null){  
  164.             if(object instanceof Collection || object instanceof Object[]){  
  165.                 jsonString = JSONArray.fromObject(object, jsonConfig).toString();  
  166.             }else{  
  167.                 jsonString = JSONObject.fromObject(object, jsonConfig).toString();  
  168.             }  
  169.         }  
  170.         return jsonString == null ? "{}" : jsonString;  
  171.     }  
  172.       
  173.     private static void setDataFormat2JAVA(){  
  174.         //设定日期转换格式  
  175.         JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"yyyy-MM-dd""yyyy-MM-dd HH:mm:ss"}));  
  176.     }  
  177.       
  178.     public static void main(String[] arg) throws Exception{  
  179.         String s = "{status : 'success'}";  
  180.         System.out.println(" object : " + JsonUtil.getJSONString(s));  
  181.     }  
  182. }  

 

 

对于java对象转换成json数据格式时,要对日期格式化常用格式,类:JsonDateValueProcessor

 

Java代码  收藏代码
  1. import java.text.SimpleDateFormat;  
  2. import java.util.Date;  
  3.   
  4. import net.sf.json.JsonConfig;  
  5. import net.sf.json.processors.JsonValueProcessor;  
  6.   
  7. /* 
  8.  * @author johncon 
  9.  * 创建日期 2008-9-10 
  10.  * json日期值处理器 
  11.  */  
  12. public class JsonDateValueProcessor implements JsonValueProcessor {  
  13.   
  14.     private String format = "yyyy-MM-dd HH:mm:ss";  
  15.   
  16.     public JsonDateValueProcessor() {  
  17.   
  18.     }  
  19.   
  20.     public JsonDateValueProcessor(String format) {  
  21.         this.format = format;  
  22.     }  
  23.   
  24.     public Object processArrayValue(Object value, JsonConfig jsonConfig) {  
  25.         return process(value, jsonConfig);  
  26.     }  
  27.   
  28.     public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {  
  29.         return process(value, jsonConfig);  
  30.     }  
  31.       
  32.     private Object process( Object value, JsonConfig jsonConfig ) {  
  33.         if (value instanceof Date) {  
  34.             String str = new SimpleDateFormat(format).format((Date) value);  
  35.             return str;  
  36.         }  
  37.         return value == null ? null : value.toString();  
  38.     }  
  39.   
  40.     public String getFormat() {  
  41.         return format;  
  42.     }  
  43.   
  44.     public void setFormat(String format) {  
  45.         this.format = format;  
  46.     }  
  47.   
  48. }  

 

 

 

对于对象中有明确类型的对象属性,可不管;但对象中有集合属性的,由于类型不明确,所以要先明确类型:

Java代码  收藏代码
  1. String jsonString = request.getParameter("json");  
  2. //增加对象中的集合属性的类型以及对象元素中的对象属性的集合属性的类型  
  3. Map clazzMap = new HashMap();  
  4. //secondItems是FirstDTO里的集合属性  
  5. clazzMap.put("secondItems", SecondDTO.class);  
  6. //thirdItems是SecondDTO里的集合属性  
  7. clazzMap.put("thirdItems", ThirdDTO.class);  
  8. FirstDTO firstDTO = (FirstDTO)JsonUtil.getDTO(jsonString, FirstDTO.class, clazzMap);  

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值