java中的json

来源:互联网 发布:手机的mac地址怎么查 编辑:程序博客网 时间:2024/05/17 02:54

java中的JSon解析  

2012-08-16 16:07:39|  分类: 默认分类|举报|字号 订阅

下载LOFTER客户端
  1. 1、DTO:Data Transfer Object,数据传送对象  
  2.   
  3. 2、对于日期格式的问题,也已经处理  
  4.   
  5. 3、json-lib-2.2.2-jdk13.jar (2.1在日期数组 json->java有问题)  
  6.   
  7. 工具类JsonUtil代码如下:  
  8.   
  9. Java代码   
  10. public class JsonUtil {     
  11.     
  12.     /**页面传至后台时,json数据在request的参数名称*/    
  13.     public final static String JSON_ATTRIBUTE = "json";     
  14.     public final static String JSON_ATTRIBUTE1 = "json1";     
  15.     public final static String JSON_ATTRIBUTE2 = "json2";     
  16.     public final static String JSON_ATTRIBUTE3 = "json3";     
  17.     public final static String JSON_ATTRIBUTE4 = "json4";     
  18.          
  19.     /**   
  20.      * 从一个JSON 对象字符格式中得到一个java对象,形如:   
  21.      * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}}   
  22.      * @param object   
  23.      * @param clazz   
  24.      * @return   
  25.      */    
  26.     public static Object getDTO(String jsonString, Class clazz){     
  27.         JSONObject jsonObject = null;     
  28.         try{     
  29.             setDataFormat2JAVA();      
  30.             jsonObject = JSONObject.fromObject(jsonString);     
  31.         }catch(Exception e){     
  32.             e.printStackTrace();     
  33.         }     
  34.         return JSONObject.toBean(jsonObject, clazz);     
  35.     }     
  36.          
  37.     /**   
  38.      * 从一个JSON 对象字符格式中得到一个java对象,其中beansList是一类的集合,形如:   
  39.      * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...},   
  40.      * beansList:[{}, {}, ...]}   
  41.      * @param jsonString   
  42.      * @param clazz   
  43.      * @param map 集合属性的类型 (key : 集合属性名, value : 集合属性类型class) eg: ("beansList" : Bean.class)   
  44.      * @return   
  45.      */    
  46.     public static Object getDTO(String jsonString, Class clazz, Map map){     
  47.         JSONObject jsonObject = null;     
  48.         try{     
  49.             setDataFormat2JAVA();      
  50.             jsonObject = JSONObject.fromObject(jsonString);     
  51.         }catch(Exception e){     
  52.             e.printStackTrace();     
  53.         }     
  54.         return JSONObject.toBean(jsonObject, clazz, map);     
  55.     }     
  56.          
  57.     /**   
  58.      * 从一个JSON数组得到一个java对象数组,形如:   
  59.      * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]   
  60.      * @param object   
  61.      * @param clazz   
  62.      * @return   
  63.      */    
  64.     public static Object[] getDTOArray(String jsonString, Class clazz){     
  65.         setDataFormat2JAVA();     
  66.         JSONArray array = JSONArray.fromObject(jsonString);     
  67.         Object[] obj = new Object[array.size()];     
  68.         for(int i = 0; i < array.size(); i++){     
  69.             JSONObject jsonObject = array.getJSONObject(i);     
  70.             obj[i] = JSONObject.toBean(jsonObject, clazz);     
  71.         }     
  72.         return obj;     
  73.     }     
  74.          
  75.     /**   
  76.      * 从一个JSON数组得到一个java对象数组,形如:   
  77.      * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]   
  78.      * @param object   
  79.      * @param clazz   
  80.      * @param map   
  81.      * @return   
  82.      */    
  83.     public static Object[] getDTOArray(String jsonString, Class clazz, Map map){     
  84.         setDataFormat2JAVA();     
  85.         JSONArray array = JSONArray.fromObject(jsonString);     
  86.         Object[] obj = new Object[array.size()];     
  87.         for(int i = 0; i < array.size(); i++){     
  88.             JSONObject jsonObject = array.getJSONObject(i);     
  89.             obj[i] = JSONObject.toBean(jsonObject, clazz, map);     
  90.         }     
  91.         return obj;     
  92.     }     
  93.          
  94.     /**   
  95.      * 从一个JSON数组得到一个java对象集合   
  96.      * @param object   
  97.      * @param clazz   
  98.      * @return   
  99.      */    
  100.     public static List getDTOList(String jsonString, Class clazz){     
  101.         setDataFormat2JAVA();     
  102.         JSONArray array = JSONArray.fromObject(jsonString);     
  103.         List list = new ArrayList();     
  104.         for(Iterator iter = array.iterator(); iter.hasNext();){     
  105.             JSONObject jsonObject = (JSONObject)iter.next();     
  106.             list.add(JSONObject.toBean(jsonObject, clazz));     
  107.         }     
  108.         return list;     
  109.     }     
  110.          
  111.     /**   
  112.      * 从一个JSON数组得到一个java对象集合,其中对象中包含有集合属性   
  113.      * @param object   
  114.      * @param clazz   
  115.      * @param map 集合属性的类型   
  116.      * @return   
  117.      */    
  118.     public static List getDTOList(String jsonString, Class clazz, Map map){     
  119.         setDataFormat2JAVA();     
  120.         JSONArray array = JSONArray.fromObject(jsonString);     
  121.         List list = new ArrayList();     
  122.         for(Iterator iter = array.iterator(); iter.hasNext();){     
  123.             JSONObject jsonObject = (JSONObject)iter.next();     
  124.             list.add(JSONObject.toBean(jsonObject, clazz, map));     
  125.         }     
  126.         return list;     
  127.     }     
  128.          
  129.     /**   
  130.      * 从json HASH表达式中获取一个map,该map支持嵌套功能   
  131.      * 形如:{"id" : "johncon", "name" : "小强"}   
  132.      * 注意commons-collections版本,必须包含org.apache.commons.collections.map.MultiKeyMap   
  133.      * @param object   
  134.      * @return   
  135.      */    
  136.     public static Map getMapFromJson(String jsonString) {     
  137.         setDataFormat2JAVA();     
  138.         JSONObject jsonObject = JSONObject.fromObject(jsonString);     
  139.         Map map = new HashMap();     
  140.         for(Iterator iter = jsonObject.keys(); iter.hasNext();){     
  141.             String key = (String)iter.next();     
  142.             map.put(key, jsonObject.get(key));     
  143.         }     
  144.         return map;     
  145.     }     
  146.          
  147.     /**   
  148.      * 从json数组中得到相应java数组   
  149.      * json形如:["123", "456"]   
  150.      * @param jsonString   
  151.      * @return   
  152.      */    
  153.     public static Object[] getObjectArrayFromJson(String jsonString) {     
  154.         JSONArray jsonArray = JSONArray.fromObject(jsonString);     
  155.         return jsonArray.toArray();     
  156.     }     
  157.     
  158.     
  159.     /**   
  160.      * 把数据对象转换成json字符串   
  161.      * DTO对象形如:{"id" : idValue, "name" : nameValue, ...}   
  162.      * 数组对象形如:[{}, {}, {}, ...]   
  163.      * map对象形如:{key1 : {"id" : idValue, "name" : nameValue, ...}, key2 : {}, ...}   
  164.      * @param object   
  165.      * @return   
  166.      */    
  167.     public static String getJSONString(Object object) throws Exception{     
  168.         String jsonString = null;     
  169.         //日期值处理器     
  170.         JsonConfig jsonConfig = new JsonConfig();     
  171.         jsonConfig.registerJsonValueProcessor(java.util.Date.classnew JsonDateValueProcessor());     
  172.         if(object != null){     
  173.             if(object instanceof Collection || object instanceof Object[]){     
  174.                 jsonString = JSONArray.fromObject(object, jsonConfig).toString();     
  175.             }else{     
  176.                 jsonString = JSONObject.fromObject(object, jsonConfig).toString();     
  177.             }     
  178.         }     
  179.         return jsonString == null ? "{}" : jsonString;     
  180.     }     
  181.          
  182.     private static void setDataFormat2JAVA(){     
  183.         //设定日期转换格式     
  184.         JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"yyyy-MM-dd""yyyy-MM-dd HH:mm:ss"}));     
  185.     }     
  186.          
  187.     public static void main(String[] arg) throws Exception{     
  188.         String s = "{status : 'success'}";     
  189.         System.out.println(" object : " + JsonUtil.getJSONString(s));     
  190.     }     
  191. }    
  192.   
  193. public class JsonUtil {  
  194.   
  195.  /**页面传至后台时,json数据在request的参数名称*/  
  196.  public final static String JSON_ATTRIBUTE = "json";  
  197.  public final static String JSON_ATTRIBUTE1 = "json1";  
  198.  public final static String JSON_ATTRIBUTE2 = "json2";  
  199.  public final static String JSON_ATTRIBUTE3 = "json3";  
  200.  public final static String JSON_ATTRIBUTE4 = "json4";  
  201.    
  202.  /** 
  203.   * 从一个JSON 对象字符格式中得到一个java对象,形如: 
  204.   * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}} 
  205.   * @param object 
  206.   * @param clazz 
  207.   * @return 
  208.   */  
  209.  public static Object getDTO(String jsonString, Class clazz){  
  210.   JSONObject jsonObject = null;  
  211.   try{  
  212.    setDataFormat2JAVA();   
  213.    jsonObject = JSONObject.fromObject(jsonString);  
  214.   }catch(Exception e){  
  215.    e.printStackTrace();  
  216.   }  
  217.   return JSONObject.toBean(jsonObject, clazz);  
  218.  }  
  219.    
  220.  /** 
  221.   * 从一个JSON 对象字符格式中得到一个java对象,其中beansList是一类的集合,形如: 
  222.   * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}, 
  223.   * beansList:[{}, {}, ...]} 
  224.   * @param jsonString 
  225.   * @param clazz 
  226.   * @param map 集合属性的类型 (key : 集合属性名, value : 集合属性类型class) eg: ("beansList" : Bean.class) 
  227.   * @return 
  228.   */  
  229.  public static Object getDTO(String jsonString, Class clazz, Map map){  
  230.   JSONObject jsonObject = null;  
  231.   try{  
  232.    setDataFormat2JAVA();   
  233.    jsonObject = JSONObject.fromObject(jsonString);  
  234.   }catch(Exception e){  
  235.    e.printStackTrace();  
  236.   }  
  237.   return JSONObject.toBean(jsonObject, clazz, map);  
  238.  }  
  239.    
  240.  /** 
  241.   * 从一个JSON数组得到一个java对象数组,形如: 
  242.   * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...] 
  243.   * @param object 
  244.   * @param clazz 
  245.   * @return 
  246.   */  
  247.  public static Object[] getDTOArray(String jsonString, Class clazz){  
  248.   setDataFormat2JAVA();  
  249.   JSONArray array = JSONArray.fromObject(jsonString);  
  250.   Object[] obj = new Object[array.size()];  
  251.   for(int i = 0; i < array.size(); i++){  
  252.    JSONObject jsonObject = array.getJSONObject(i);  
  253.    obj[i] = JSONObject.toBean(jsonObject, clazz);  
  254.   }  
  255.   return obj;  
  256.  }  
  257.    
  258.  /** 
  259.   * 从一个JSON数组得到一个java对象数组,形如: 
  260.   * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...] 
  261.   * @param object 
  262.   * @param clazz 
  263.   * @param map 
  264.   * @return 
  265.   */  
  266.  public static Object[] getDTOArray(String jsonString, Class clazz, Map map){  
  267.   setDataFormat2JAVA();  
  268.   JSONArray array = JSONArray.fromObject(jsonString);  
  269.   Object[] obj = new Object[array.size()];  
  270.   for(int i = 0; i < array.size(); i++){  
  271.    JSONObject jsonObject = array.getJSONObject(i);  
  272.    obj[i] = JSONObject.toBean(jsonObject, clazz, map);  
  273.   }  
  274.   return obj;  
  275.  }  
  276.    
  277.  /** 
  278.   * 从一个JSON数组得到一个java对象集合 
  279.   * @param object 
  280.   * @param clazz 
  281.   * @return 
  282.   */  
  283.  public static List getDTOList(String jsonString, Class clazz){  
  284.   setDataFormat2JAVA();  
  285.   JSONArray array = JSONArray.fromObject(jsonString);  
  286.   List list = new ArrayList();  
  287.   for(Iterator iter = array.iterator(); iter.hasNext();){  
  288.    JSONObject jsonObject = (JSONObject)iter.next();  
  289.    list.add(JSONObject.toBean(jsonObject, clazz));  
  290.   }  
  291.   return list;  
  292.  }  
  293.    
  294.  /** 
  295.   * 从一个JSON数组得到一个java对象集合,其中对象中包含有集合属性 
  296.   * @param object 
  297.   * @param clazz 
  298.   * @param map 集合属性的类型 
  299.   * @return 
  300.   */  
  301.  public static List getDTOList(String jsonString, Class clazz, Map map){  
  302.   setDataFormat2JAVA();  
  303.   JSONArray array = JSONArray.fromObject(jsonString);  
  304.   List list = new ArrayList();  
  305.   for(Iterator iter = array.iterator(); iter.hasNext();){  
  306.    JSONObject jsonObject = (JSONObject)iter.next();  
  307.    list.add(JSONObject.toBean(jsonObject, clazz, map));  
  308.   }  
  309.   return list;  
  310.  }  
  311.    
  312.  /** 
  313.   * 从json HASH表达式中获取一个map,该map支持嵌套功能 
  314.   * 形如:{"id" : "johncon", "name" : "小强"} 
  315.   * 注意commons-collections版本,必须包含org.apache.commons.collections.map.MultiKeyMap 
  316.   * @param object 
  317.   * @return 
  318.   */  
  319.  public static Map getMapFromJson(String jsonString) {  
  320.   setDataFormat2JAVA();  
  321.         JSONObject jsonObject = JSONObject.fromObject(jsonString);  
  322.         Map map = new HashMap();  
  323.         for(Iterator iter = jsonObject.keys(); iter.hasNext();){  
  324.             String key = (String)iter.next();  
  325.             map.put(key, jsonObject.get(key));  
  326.         }  
  327.         return map;  
  328.     }  
  329.    
  330.  /** 
  331.      * 从json数组中得到相应java数组 
  332.      * json形如:["123", "456"] 
  333.      * @param jsonString 
  334.      * @return 
  335.      */  
  336.     public static Object[] getObjectArrayFromJson(String jsonString) {  
  337.         JSONArray jsonArray = JSONArray.fromObject(jsonString);  
  338.         return jsonArray.toArray();  
  339.     }  
  340.   
  341.   
  342.  /** 
  343.   * 把数据对象转换成json字符串 
  344.   * DTO对象形如:{"id" : idValue, "name" : nameValue, ...} 
  345.   * 数组对象形如:[{}, {}, {}, ...] 
  346.   * map对象形如:{key1 : {"id" : idValue, "name" : nameValue, ...}, key2 : {}, ...} 
  347.   * @param object 
  348.   * @return 
  349.   */  
  350.  public static String getJSONString(Object object) throws Exception{  
  351.   String jsonString = null;  
  352.   //日期值处理器  
  353.   JsonConfig jsonConfig = new JsonConfig();  
  354.   jsonConfig.registerJsonValueProcessor(java.util.Date.classnew JsonDateValueProcessor());  
  355.   if(object != null){  
  356.    if(object instanceof Collection || object instanceof Object[]){  
  357.     jsonString = JSONArray.fromObject(object, jsonConfig).toString();  
  358.    }else{  
  359.     jsonString = JSONObject.fromObject(object, jsonConfig).toString();  
  360.    }  
  361.   }  
  362.   return jsonString == null ? "{}" : jsonString;  
  363.  }  
  364.    
  365.  private static void setDataFormat2JAVA(){  
  366.   //设定日期转换格式  
  367.   JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"yyyy-MM-dd""yyyy-MM-dd HH:mm:ss"}));  
  368.  }  
  369.    
  370.  public static void main(String[] arg) throws Exception{  
  371.   String s = "{status : 'success'}";  
  372.   System.out.println(" object : " + JsonUtil.getJSONString(s));  
  373.  }  
  374. }   
  375.   
  376. 对于java对象转换成json数据格式时,要对日期格式化常用格式,类:JsonDateValueProcessor  
  377.   
  378. Java代码   
  379. import java.text.SimpleDateFormat;     
  380. import java.util.Date;     
  381.     
  382. import net.sf.json.JsonConfig;     
  383. import net.sf.json.processors.JsonValueProcessor;     
  384.     
  385. /*   
  386.  * @author johncon   
  387.  * 创建日期 2008-9-10   
  388.  * json日期值处理器   
  389.  */    
  390. public class JsonDateValueProcessor implements JsonValueProcessor {     
  391.     
  392.     private String format = "yyyy-MM-dd HH:mm:ss";     
  393.     
  394.     public JsonDateValueProcessor() {     
  395.     
  396.     }     
  397.     
  398.     public JsonDateValueProcessor(String format) {     
  399.         this.format = format;     
  400.     }     
  401.     
  402.     public Object processArrayValue(Object value, JsonConfig jsonConfig) {     
  403.         return process(value, jsonConfig);     
  404.     }     
  405.     
  406.     public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {     
  407.         return process(value, jsonConfig);     
  408.     }     
  409.          
  410.     private Object process( Object value, JsonConfig jsonConfig ) {     
  411.         if (value instanceof Date) {     
  412.             String str = new SimpleDateFormat(format).format((Date) value);     
  413.             return str;     
  414.         }     
  415.         return value == null ? null : value.toString();     
  416.     }     
  417.     
  418.     public String getFormat() {     
  419.         return format;     
  420.     }     
  421.     
  422.     public void setFormat(String format) {     
  423.         this.format = format;     
  424.     }     
  425.     
  426. }    
  427.   
  428. import java.text.SimpleDateFormat;  
  429. import java.util.Date;  
  430.   
  431. import net.sf.json.JsonConfig;  
  432. import net.sf.json.processors.JsonValueProcessor;  
  433.   
  434. /* 
  435.  * @author johncon 
  436.  * 创建日期 2008-9-10 
  437.  * json日期值处理器 
  438.  */  
  439. public class JsonDateValueProcessor implements JsonValueProcessor {  
  440.   
  441.  private String format = "yyyy-MM-dd HH:mm:ss";  
  442.   
  443.  public JsonDateValueProcessor() {  
  444.   
  445.  }  
  446.   
  447.  public JsonDateValueProcessor(String format) {  
  448.   this.format = format;  
  449.  }  
  450.   
  451.  public Object processArrayValue(Object value, JsonConfig jsonConfig) {  
  452.   return process(value, jsonConfig);  
  453.  }  
  454.   
  455.  public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {  
  456.   return process(value, jsonConfig);  
  457.  }  
  458.    
  459.  private Object process( Object value, JsonConfig jsonConfig ) {  
  460.   if (value instanceof Date) {  
  461.    String str = new SimpleDateFormat(format).format((Date) value);  
  462.    return str;  
  463.   }  
  464.   return value == null ? null : value.toString();  
  465.  }  
  466.   
  467.  public String getFormat() {  
  468.   return format;  
  469.  }  
  470.   
  471.  public void setFormat(String format) {  
  472.   this.format = format;  
  473.  }  
  474.   
  475. }   
  476.   
  477. 对于对象中有明确类型的对象属性,可不管;但对象中有集合属性的,由于类型不明确,所以要先明确类型:  
  478.   
  479. Java代码   
  480. String jsonString = request.getParameter("json");     
  481. //增加对象中的集合属性的类型以及对象元素中的对象属性的集合属性的类型     
  482. Map clazzMap = new HashMap();     
  483. //secondItems是FirstDTO里的集合属性     
  484. clazzMap.put("secondItems", SecondDTO.class);     
  485. //thirdItems是SecondDTO里的集合属性     
  486. clazzMap.put("thirdItems", ThirdDTO.class);     
  487. FirstDTO firstDTO = (FirstDTO)JsonUtil.getDTO(jsonString, FirstDTO.class, clazzMap); 
0 0