Convert between Java and json objects

  • 2020-04-01 03:01:57
  • OfStack

Json-lib is a Java library that provides the ability to convert Java objects, including beans, maps, collections, Java arrays and XML, into json or vice versa.

 

2. The json - lib homepage: http://json-lib.sourceforge.net/

 

3. Execution environment

        The following class library support is required

Commons lang - 2.5
Commons - beanutils 1.8.0 comes with
The Commons - the collections 3.2.1
Commons - logging 1.1.1
Ezmorph 1.0.6
4. Functional examples

    Here is a code example with a junit-case example


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 {
    /*
     *   General type, List , Collection Is used JSONArray parsing 
     *  
     *  Map , custom types are used JSONObject parsing 
     *   Can be Map Understood as an object, inside key/value Properties that can be understood as objects / Attribute values 
     *   namely {key1:value1,key2,value2......}
     * 
     * 1.JSONObject Is a name:values Set through it get(key) The method gets this key After the corresponding value Part of the ( string )
     *          Through its getJSONObject(key) I can take one JSONObject . -->  Converted to map,
     *          Through its getJSONArray(key)  I can take one JSONArray  . 
     * 
     * 
     */

    //Normally an array is converted to 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]  
    }

    
    //Convert the Collection object to 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"]  
    }

    
    //The string json is converted to json, using JSONArray or JSONObject, as the case may be
    @Test
    public void testJsonStrToJSON(){
        JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );  
        System.out.println( jsonArray );  
        // prints ["json","is","easy"]  
    }

    
    //Map is converted to json using 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 );  
    }

    //The composite bean is converted to json
    @Test
    public void testBeadToJSON(){
        MyBean bean = new MyBean();
        bean.setId("001");
        bean.setName(" Bank card ");
        bean.setDate(new Date());

        List cardNum = new ArrayList();
        cardNum.add(" The ABC ");
        cardNum.add(" icbc ");
        cardNum.add(" The construction bank ");
        cardNum.add(new Person("test"));

        bean.setCardNum(cardNum);

        JSONObject jsonObject = JSONObject.fromObject(bean);
        System.out.println(jsonObject);

    }

    //Json of normal type is converted to objects
    @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);
        }

    }

    
    //Parse the json into a composite type object that contains the 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());
            }
        }
    }

    
    //Parse the json into a composite type object, including a Map
    @Test
    public void testJSONToBeanHavaMap(){
        //Think of a Map as an object
        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);
        //Using hinting, the json is directly parsed into the specified custom object, where the List is fully parsed and the Map is not
        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");

        //To register the converter in the registrar first, you need to use the classes in the ezmorph package
        MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();
        Morpher dynaMorpher = new BeanMorpher( Person.class,  morpherRegistry);  
        morpherRegistry.registerMorpher( dynaMorpher );  

        
        Map map = diyBean.getMap();
        
        System.out.println(map);
      
        List<Person> output = new ArrayList();  
        for( Iterator i = map.values().iterator(); i.hasNext(); ){  
            //The specified DynaBean is transformed using the registry
           output.add( (Person)morpherRegistry.morph( Person.class, i.next() ) );  
        }  

        for(Person p : output){
            System.out.println(p.getName());
        
        }

    }      
}

5. The resources required for the above example, including jars and code, are provided below
/Files/mailingfeng/json-lib/json-lib use case required jar package and Java class. Rar


Related articles: