• 使用json-lib进行Java和JSON之间的转换 [转]


    [转] http://www.cnblogs.com/mailingfeng/archive/2012/01/18/2325707.html

    1. json-lib是一个java类库,提供将Java对象,包括beans, maps, collections, java arrays and XML等转换成JSON,或者反向转换的功能。

    2. json-lib 主页 : http://json-lib.sourceforge.net/

    3.执行环境

         需要以下类库支持

    • jakarta commons-lang 2.5
    • jakarta commons-beanutils 1.8.0
    • jakarta commons-collections 3.2.1
    • jakarta commons-logging 1.1.1
    • ezmorph 1.0.6

    4.功能示例

       这里通过JUnit-Case例子给出代码示例

      1 package com.mai.json;
      2 
      3 import static org.junit.Assert.assertEquals;
      4 
      5 import java.util.ArrayList;
      6 import java.util.Date;
      7 import java.util.HashMap;
      8 import java.util.Iterator;
      9 import java.util.List;
     10 import java.util.Map;
     11 import net.sf.ezmorph.Morpher;
     12 import net.sf.ezmorph.MorpherRegistry;
     13 import net.sf.ezmorph.bean.BeanMorpher;
     14 import net.sf.json.JSONArray;
     15 import net.sf.json.JSONObject;
     16 import net.sf.json.util.JSONUtils;
     17 
     18 import org.apache.commons.beanutils.PropertyUtils;
     19 import org.junit.Test;
     20 
     21 public class JsonLibTest {
     22 
     23     /*
     24      *  普通类型、List、Collection等都是用JSONArray解析
     25      *  
     26      *  Map、自定义类型是用JSONObject解析
     27      *  可以将Map理解成一个对象,里面的key/value对可以理解成对象的属性/属性值
     28      *  即{key1:value1,key2,value2......}
     29      * 
     30      * 1.JSONObject是一个name:values集合,通过它的get(key)方法取得的是key后对应的value部分(字符串)
     31      *         通过它的getJSONObject(key)可以取到一个JSONObject,--> 转换成map,
     32      *         通过它的getJSONArray(key) 可以取到一个JSONArray ,
     33      * 
     34      * 
     35      */
     36     
     37     //一般数组转换成JSON
     38     @Test
     39     public void testArrayToJSON(){
     40         boolean[] boolArray = new boolean[]{true,false,true};  
     41         JSONArray jsonArray = JSONArray.fromObject( boolArray );  
     42         System.out.println( jsonArray );  
     43         // prints [true,false,true]  
     44     }
     45     
     46     
     47     //Collection对象转换成JSON
     48     @Test
     49     public void testListToJSON(){
     50         List list = new ArrayList();  
     51         list.add( "first" );  
     52         list.add( "second" );  
     53         JSONArray jsonArray = JSONArray.fromObject( list );  
     54         System.out.println( jsonArray );  
     55         // prints ["first","second"]  
     56     }
     57     
     58     
     59     //字符串json转换成json, 根据情况是用JSONArray或JSONObject
     60     @Test
     61     public void testJsonStrToJSON(){
     62         JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );  
     63         System.out.println( jsonArray );  
     64         // prints ["json","is","easy"]  
     65     }
     66     
     67     
     68     //Map转换成json, 是用jsonObject
     69     @Test
     70     public void testMapToJSON(){
     71         Map map = new HashMap();  
     72         map.put( "name", "json" );  
     73         map.put( "bool", Boolean.TRUE );  
     74         map.put( "int", new Integer(1) );  
     75         map.put( "arr", new String[]{"a","b"} );  
     76         map.put( "func", "function(i){ return this.arr[i]; }" );  
     77           
     78         JSONObject jsonObject = JSONObject.fromObject( map );  
     79         System.out.println( jsonObject );  
     80     }
     81     
     82     //复合类型bean转成成json
     83     @Test
     84     public void testBeadToJSON(){
     85         MyBean bean = new MyBean();
     86         bean.setId("001");
     87         bean.setName("银行卡");
     88         bean.setDate(new Date());
     89         
     90         List cardNum = new ArrayList();
     91         cardNum.add("农行");
     92         cardNum.add("工行");
     93         cardNum.add("建行");
     94         cardNum.add(new Person("test"));
     95         
     96         bean.setCardNum(cardNum);
     97         
     98         JSONObject jsonObject = JSONObject.fromObject(bean);
     99         System.out.println(jsonObject);
    100         
    101     }
    102     
    103     //普通类型的json转换成对象
    104     @Test
    105     public void testJSONToObject() throws Exception{
    106         String json = "{name="json",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";  
    107         JSONObject jsonObject = JSONObject.fromObject( json ); 
    108         System.out.println(jsonObject);
    109         Object bean = JSONObject.toBean( jsonObject ); 
    110         assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) );  
    111         assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) );  
    112         assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) );  
    113         assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) );  
    114         assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) );  
    115         System.out.println(PropertyUtils.getProperty(bean, "name"));
    116         System.out.println(PropertyUtils.getProperty(bean, "bool"));
    117         System.out.println(PropertyUtils.getProperty(bean, "int"));
    118         System.out.println(PropertyUtils.getProperty(bean, "double"));
    119         System.out.println(PropertyUtils.getProperty(bean, "func"));
    120         System.out.println(PropertyUtils.getProperty(bean, "array"));
    121         
    122         List arrayList = (List)JSONArray.toCollection(jsonObject.getJSONArray("array"));
    123         for(Object object : arrayList){
    124             System.out.println(object);
    125         }
    126         
    127     }
    128     
    129     
    130     //将json解析成复合类型对象, 包含List
    131     @Test
    132     public void testJSONToBeanHavaList(){
    133         String json = "{list:[{name:'test1'},{name:'test2'}],map:{test1:{name:'test1'},test2:{name:'test2'}}}";
    134 //        String json = "{list:[{name:'test1'},{name:'test2'}]}";
    135         Map classMap = new HashMap();
    136         classMap.put("list", Person.class);
    137         MyBeanWithPerson diyBean = (MyBeanWithPerson)JSONObject.toBean(JSONObject.fromObject(json),MyBeanWithPerson.class , classMap);
    138         System.out.println(diyBean);
    139         
    140         List list = diyBean.getList();
    141         for(Object o : list){
    142             if(o instanceof Person){
    143                 Person p = (Person)o;
    144                 System.out.println(p.getName());
    145             }
    146         }
    147     }
    148     
    149     
    150     //将json解析成复合类型对象, 包含Map
    151     @Test
    152     public void testJSONToBeanHavaMap(){
    153         //把Map看成一个对象
    154         String json = "{list:[{name:'test1'},{name:'test2'}],map:{testOne:{name:'test1'},testTwo:{name:'test2'}}}";
    155         Map classMap = new HashMap();
    156         classMap.put("list", Person.class);
    157         classMap.put("map", Map.class);
    158         //使用暗示,直接将json解析为指定自定义对象,其中List完全解析,Map没有完全解析
    159         MyBeanWithPerson diyBean = (MyBeanWithPerson)JSONObject.toBean(JSONObject.fromObject(json),MyBeanWithPerson.class , classMap);
    160         System.out.println(diyBean);
    161         
    162         System.out.println("do the list release");
    163         List<Person> list = diyBean.getList();
    164         for(Person o : list){
    165             Person p = (Person)o;
    166             System.out.println(p.getName());
    167         }
    168         
    169         System.out.println("do the map release");
    170         
    171         //先往注册器中注册变换器,需要用到ezmorph包中的类
    172         MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();
    173         Morpher dynaMorpher = new BeanMorpher( Person.class,  morpherRegistry);  
    174         morpherRegistry.registerMorpher( dynaMorpher );  
    175         
    176         
    177         Map map = diyBean.getMap();
    178         /*这里的map没进行类型暗示,故按默认的,里面存的为net.sf.ezmorph.bean.MorphDynaBean类型的对象*/
    179         System.out.println(map);
    180       /*输出:
    181         {testOne=net.sf.ezmorph.bean.MorphDynaBean@f73c1[
    182           {name=test1}
    183         ], testTwo=net.sf.ezmorph.bean.MorphDynaBean@186c6b2[
    184           {name=test2}
    185         ]}
    186       */
    187         List<Person> output = new ArrayList();  
    188         for( Iterator i = map.values().iterator(); i.hasNext(); ){  
    189             //使用注册器对指定DynaBean进行对象变换
    190            output.add( (Person)morpherRegistry.morph( Person.class, i.next() ) );  
    191         }  
    192         
    193         for(Person p : output){
    194             System.out.println(p.getName());
    195         /*输出:
    196           test1
    197           test2
    198         */
    199         }
    200         
    201     }
    202     
    203     
    204     
    205 }
    206 .下面提供上面例子所需的资源,包括jar包和代码
    207 /Files/mailingfeng/json-lib/json-lib用例所需jar包和java类.rar

    -------------------- 补充 ---------------------

    [转] http://zhidao.baidu.com/question/459016631.html

    [注] 一些接口不一定对,参照上文 

    json格式如下:{"response":{"data":[{"address":"南京市游乐园","province":"江苏","district":"玄武区","city":"南京"}]},"status":"ok"}
    希望得到结果是: 江苏 南京 玄武区 南京市游乐园

    JSONObject  dataJson=new JSONObject("你的Json数据“);
    JSONObject response=dataJson.getJSONObject("response");
    JSONArray data=response.getJSONArray("data");
    JSONObject info=data.getJSONObject(0);
    String province=info.getString("province");
    String city=info.getString("city");
    String district=info.getString("district");
    String address=info.getString("address");
    System.out.println(province+city+district+address);
  • 相关阅读:
    大型网站优化-memcache技术
    MySQL常见注意事项及优化
    网站优化—mysql explain执行计划
    网站优化—MySQL优化
    网站优化—页面静态化技术
    防盗链案例
    伪静态的实现
    (19) PHP 随笔---LAMP 系统常用命令
    (17) PHP 随笔---LAMP vi编辑器
    (18) PHP 随笔---LAMP 权限操作
  • 原文地址:https://www.cnblogs.com/longdouhzt/p/3143486.html
Copyright © 2020-2023  润新知