欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 和 json 对象间转换

程序员文章站 2024-02-23 11:32:58
1. json-lib是一个java类库,提供将java对象,包括beans, maps, collections, java arrays and xml等转换成json...

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

 

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

 

3.执行环境

     需要以下类库支持

commons-lang 2.5
commons-beanutils 1.8.0
commons-collections 3.2.1
commons-logging 1.1.1
ezmorph 1.0.6
4.功能示例

   这里通过junit-case例子给出代码示例

复制代码 代码如下:

package com.mai.json;

import static org.junit.assert.assertequals;

import java.util.arraylist;
import java.util.date;
import java.util.hashmap;
import java.util.iterator;
import java.util.list;
import java.util.map;
import net.sf.ezmorph.morpher;
import net.sf.ezmorph.morpherregistry;
import net.sf.ezmorph.bean.beanmorpher;
import net.sf.json.jsonarray;
import net.sf.json.jsonobject;
import net.sf.json.util.jsonutils;

import org.apache.commons.beanutils.propertyutils;
import org.junit.test;

public class jsonlibtest {

    /*
     *  普通类型、list、collection等都是用jsonarray解析
     * 
     *  map、自定义类型是用jsonobject解析
     *  可以将map理解成一个对象,里面的key/value对可以理解成对象的属性/属性值
     *  即{key1:value1,key2,value2......}
     *
     * 1.jsonobject是一个name:values集合,通过它的get(key)方法取得的是key后对应的value部分(字符串)
     *         通过它的getjsonobject(key)可以取到一个jsonobject,--> 转换成map,
     *         通过它的getjsonarray(key) 可以取到一个jsonarray ,
     *
     *
     */

    //一般数组转换成json
    @test
    public void testarraytojson(){
        boolean[] boolarray = new boolean[]{true,false,true}; 
        jsonarray jsonarray = jsonarray.fromobject( boolarray ); 
        system.out.println( jsonarray ); 
        // prints [true,false,true] 
    }

   
    //collection对象转换成json
    @test
    public void testlisttojson(){
        list list = new arraylist(); 
        list.add( "first" ); 
        list.add( "second" ); 
        jsonarray jsonarray = jsonarray.fromobject( list ); 
        system.out.println( jsonarray ); 
        // prints ["first","second"] 
    }

   
    //字符串json转换成json, 根据情况是用jsonarray或jsonobject
    @test
    public void testjsonstrtojson(){
        jsonarray jsonarray = jsonarray.fromobject( "['json','is','easy']" ); 
        system.out.println( jsonarray ); 
        // prints ["json","is","easy"] 
    }

   
    //map转换成json, 是用jsonobject
    @test
    public void testmaptojson(){
        map map = new hashmap(); 
        map.put( "name", "json" ); 
        map.put( "bool", boolean.true ); 
        map.put( "int", new integer(1) ); 
        map.put( "arr", new string[]{"a","b"} ); 
        map.put( "func", "function(i){ return this.arr[i]; }" ); 

        jsonobject jsonobject = jsonobject.fromobject( map ); 
        system.out.println( jsonobject ); 
    }

    //复合类型bean转成成json
    @test
    public void testbeadtojson(){
        mybean bean = new mybean();
        bean.setid("001");
        bean.setname("银行卡");
        bean.setdate(new date());

        list cardnum = new arraylist();
        cardnum.add("农行");
        cardnum.add("工行");
        cardnum.add("建行");
        cardnum.add(new person("test"));

        bean.setcardnum(cardnum);

        jsonobject jsonobject = jsonobject.fromobject(bean);
        system.out.println(jsonobject);

    }

    //普通类型的json转换成对象
    @test
    public void testjsontoobject() throws exception{
        string json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}"; 
        jsonobject jsonobject = jsonobject.fromobject( json );
        system.out.println(jsonobject);
        object bean = jsonobject.tobean( jsonobject );
        assertequals( jsonobject.get( "name" ), propertyutils.getproperty( bean, "name" ) ); 
        assertequals( jsonobject.get( "bool" ), propertyutils.getproperty( bean, "bool" ) ); 
        assertequals( jsonobject.get( "int" ), propertyutils.getproperty( bean, "int" ) ); 
        assertequals( jsonobject.get( "double" ), propertyutils.getproperty( bean, "double" ) ); 
        assertequals( jsonobject.get( "func" ), propertyutils.getproperty( bean, "func" ) ); 
        system.out.println(propertyutils.getproperty(bean, "name"));
        system.out.println(propertyutils.getproperty(bean, "bool"));
        system.out.println(propertyutils.getproperty(bean, "int"));
        system.out.println(propertyutils.getproperty(bean, "double"));
        system.out.println(propertyutils.getproperty(bean, "func"));
        system.out.println(propertyutils.getproperty(bean, "array"));

        list arraylist = (list)jsonarray.tocollection(jsonobject.getjsonarray("array"));
        for(object object : arraylist){
            system.out.println(object);
        }

    }

   
    //将json解析成复合类型对象, 包含list
    @test
    public void testjsontobeanhavalist(){
        string json = "{list:[{name:'test1'},{name:'test2'}],map:{test1:{name:'test1'},test2:{name:'test2'}}}";
//        string json = "{list:[{name:'test1'},{name:'test2'}]}";
        map classmap = new hashmap();
        classmap.put("list", person.class);
        mybeanwithperson diybean = (mybeanwithperson)jsonobject.tobean(jsonobject.fromobject(json),mybeanwithperson.class , classmap);
        system.out.println(diybean);

        list list = diybean.getlist();
        for(object o : list){
            if(o instanceof person){
                person p = (person)o;
                system.out.println(p.getname());
            }
        }
    }

   
    //将json解析成复合类型对象, 包含map
    @test
    public void testjsontobeanhavamap(){
        //把map看成一个对象
        string json = "{list:[{name:'test1'},{name:'test2'}],map:{testone:{name:'test1'},testtwo:{name:'test2'}}}";
        map classmap = new hashmap();
        classmap.put("list", person.class);
        classmap.put("map", map.class);
        //使用暗示,直接将json解析为指定自定义对象,其中list完全解析,map没有完全解析
        mybeanwithperson diybean = (mybeanwithperson)jsonobject.tobean(jsonobject.fromobject(json),mybeanwithperson.class , classmap);
        system.out.println(diybean);

        system.out.println("do the list release");
        list<person> list = diybean.getlist();
        for(person o : list){
            person p = (person)o;
            system.out.println(p.getname());
        }

        system.out.println("do the map release");

        //先往注册器中注册变换器,需要用到ezmorph包中的类
        morpherregistry morpherregistry = jsonutils.getmorpherregistry();
        morpher dynamorpher = new beanmorpher( person.class,  morpherregistry); 
        morpherregistry.registermorpher( dynamorpher ); 

       
        map map = diybean.getmap();
        /*这里的map没进行类型暗示,故按默认的,里面存的为net.sf.ezmorph.bean.morphdynabean类型的对象*/
        system.out.println(map);
      /*输出:
        {testone=net.sf.ezmorph.bean.morphdynabean@f73c1[
          {name=test1}
        ], testtwo=net.sf.ezmorph.bean.morphdynabean@186c6b2[
          {name=test2}
        ]}
      */
        list<person> output = new arraylist(); 
        for( iterator i = map.values().iterator(); i.hasnext(); ){ 
            //使用注册器对指定dynabean进行对象变换
           output.add( (person)morpherregistry.morph( person.class, i.next() ) ); 
        } 

        for(person p : output){
            system.out.println(p.getname());
        /*输出:
          test1
          test2
        */
        }

    }     
}


5.下面提供上面例子所需的资源,包括jar包和代码
/files/mailingfeng/json-lib/json-lib用例所需jar包和java类.rar