【转】细细品味Web——Json-Lib类库使用手册

1、JsonLib简介

    Json-lib包 是一个Java类库,提供将Java对象 (包括:beans,maps,collections,java arrays 和 XML等)和JSON互相转换 功能

    相关的Jar包:

 

  • json-lib-2.3-jdk15.jar
  • commons-beanutils-1.8.0.jar
  • commons-collections-3.1.jar
  • commons-lang-2.4.jar
  • commons-logging-1.1.1.jar
  • ezmorph-1.0.6.jar

 

    备注 :我们这里用的Struts-2.3.3版本中Json-lib包。

    官方网站:http://json-lib.sourceforge.net/

 

    下表中是Java与JavaScript类型对应关系。

 

JSON

 

Java

string

<=>

java.lang.String, java.lang.Character, char

number

<=>

java.lang.Number, byte, short, int, long, float, double

true|false  

<=>  

java.lang.Boolean, boolean  

null

<=>

null

function  

<=>

net.sf.json.JSONFunction  

array  

<=>

net.sf.json.JSONArray (object, string, number, boolean, function)  

object  

<=>

net.sf.json.JSONObject  

 

2、JsonLib使用

2.1 准备工作

    我们这里使用JUnit4.0进行测试实验,下面是测试中使用中的类。

    【测试实体——Student

 

package com.hebut.jsonlib;

 

public class Student {

    private String userName;

    private String sex;

    private int age;

   

    public Student() {

    }

   

    public Student(String userName, String sex, int age) {

        this .userName = userName;

        this .sex = sex;

        this .age = age;

    }

 

    public String getUserName() {

        return userName;

    }

    public void setUserName(String userName) {

        this .userName = userName;

    }

    public String getSex() {

        return sex;

    }

   

    public void setSex(String sex) {

        this .sex = sex;

    }

    public int getAge() {

        return age;

    }

    public void setAge(int age) {

        this .age = age;

    }

}

 

    【测试实体——Class

 

package com.hebut.jsonlib;

 

import java.util.Date;

import java.util.List;

 

public class Class {

    private String name;

    private Date date;

    private List<Student> students;

   

    public Class() {

    }

   

    public Class(String name, Date date, List<Student> students) {

        this .name = name;

        this .date = date;

        this .students = students;

    }

   

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this .name = name;

    }

    public Date getDate() {

        return date;

    }

    public void setDate(Date date) {

        this .date = date;

    }

    public List<Student> getStudents() {

        return students;

    }

    public void setStudents(List<Student> students) {

        this .students = students;

    }

}

 

2.2 处理ArraysToJson

    【示例代码

 

package com.hebut.jsonlib;

 

import java.util.ArrayList;

import java.util.List;

import net.sf.json.JSONArray;

import org.junit.Test;

 

public class JsonLib {

 

    @Test

    public void array2json() {

        int [] intArray = new int []{1,4,5};

        JSONArray jsonArray1 = JSONArray.fromObject (intArray);

        System.out .println("int[] intArray");

        System.out .println(jsonArray1);

       

        boolean [] boolArray = new boolean []{true ,false ,true };

        System.out .println("boolean[] boolArray");

        JSONArray jsonArray2 = JSONArray.fromObject (boolArray);

        System.out .println(jsonArray2);

       

        int [][] int2Array = new int [][]{{1,2},{3,4}};

        JSONArray jsonArray3 = JSONArray.fromObject (int2Array);

        System.out .println("int[][] int2Array");

        System.out .println(jsonArray3);

       

        float [] floatArray = new float []{0.1f,0.2f,0.3f};

        JSONArray jsonArray4 = JSONArray.fromObject (floatArray);

        System.out .println("float[] floatArray");

        System.out .println(jsonArray4);

       

        String[] strArray = new String[]{"hello","hebut","xiapi"};

        JSONArray jsonArray5 = JSONArray.fromObject (strArray);

        System.out .println("String[] strArray");

        System.out .println(jsonArray5);

    }

}

 

    【运行结果

 

int[] intArray

[1,4,5]

boolean[] boolArray

[true,false,true]

int[][] int2Array

[[1,2],[3,4]]

float[] floatArray

[0.1,0.2,0.3]

String[] strArray

["hello","hebut","xiapi"]

 

2.3 处理CollectionsToJson

    【示例代码

 

package com.hebut.jsonlib;

 

import java.util.ArrayList;

import java.util.List;

import net.sf.json.JSONArray;

import org.junit.Test;

 

public class JsonLib {

   

    @Test

    public void collections2json(){

        List list1 = new ArrayList();

        list1.add("first");

        list1.add("second");

        JSONArray jsonArray1 = JSONArray.fromObject (list1);

        System.out .println("List list1");

        System.out .println(jsonArray1);

       

        List<Student> list2 = new ArrayList<Student>();

        list2.add(new Student("xiapi1"," ",10));

        list2.add(new Student("xiapi2"," ",11));

        list2.add(new Student("xiapi3"," ",12));

        JSONArray jsonArray2 = JSONArray.fromObject (list2);

        System.out .println("List<Student> list2");

        System.out .println(jsonArray2);

    }

}

 

    【运行结果

 

List list1

["first","second"]

List<Student> list2

[{"age":10,"sex":" ","userName":"xiapi1"},{"age":11,"sex":" ","userName":"xiapi2"},{"age":12,"sex":" ","userName":"xiapi3"}]

 

2.4 处理MapToJson

    【示例代码

 

package com.hebut.jsonlib;

 

import java.util.HashMap;

import java.util.Map;

import net.sf.json.JSONObject;

import org.junit.Test;

 

public class JsonLib {

   

    @Test

    public void map2json(){

        Map map1 = new HashMap();

        map1.put("name","json");

        map1.put("bool",Boolean.TRUE );

        map1.put("int",new Integer(1));

        map1.put("arr",new String[]{"a","b"});

        map1.put("func","function(i){ return this.arr[i]; }");

        JSONObject jsonObject1 = JSONObject.fromObject (map1);

        System.out .println("Map map1");

        System.out .println(jsonObject1);

       

        Map<String,Student> map2 = new HashMap<String,Student>();

        map2.put("k1", new Student("xiapi1"," ",10));

        map2.put("k2", new Student("xiapi2"," ",12));

        map2.put("k3", new Student("xiapi3"," ",13));

        JSONObject jsonObject2 = JSONObject.fromObject (map2);

        System.out .println("Map<String,Student> map2");

        System.out .println(jsonObject2);

    }

}

 

    【运行结果

 

Map map1

{"arr":["a","b"],"int":1,"name":"json","func":function(i){ return this.arr[i]; },"bool":true}

Map<String,Student> map2

{"k3":{"age":13,"sex":" ","userName":"xiapi3"},"k1":{"age":10,"sex":" ","userName":"xiapi1"},"k2":{"age":12,"sex":" ","userName":"xiapi2"}}

 

2.5 处理BeanToJson

    【示例代码

 

package com.hebut.jsonlib;

 

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

 

import net.sf.json.JSON;

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

import net.sf.json.JsonConfig;

import net.sf.json.processors.JsonValueProcessor;

import net.sf.json.util.CycleDetectionStrategy;

import org.junit.Test;

 

public class JsonLib {

   

    @Test

    public void bean2json(){

        Student s1 = new Student("xiapi"," ",22);

        JSONObject jsonObject1 = JSONObject.fromObject (s1);

        System.out .println("Student s1");

        System.out .println(jsonObject1);

       

        Class c1 = new Class();

        c1.setName(" 计算机应用 1 ");

        c1.setDate(new Date());

        JsonConfig config=new JsonConfig();

        // 设置循环策略为忽略

        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT );

        // 设置 json 转换的处理器用来处理日期类型

        // 凡是反序列化 Date 类型的对象,都会经过该处理器进行处理

        config.registerJsonValueProcessor(Date.class ,

                                    new JsonValueProcessor() {

            // 参数 1 :属性名 参数 2 json 对象的值 参数 3 jsonConfig 对象

            public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {

                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Date d=(Date) arg1;

                return sdf.format(d);

            }

            public Object processArrayValue(Object arg0, JsonConfig arg1) {

                return null ;

            }

        });

        List<Student> students = new ArrayList<Student>();

        students.add(new Student("xiapi1"," ",10));

        students.add(new Student("xiapi2"," ",11));

        students.add(new Student("xiapi3"," ",12));

        c1.setStudents(students);

        JSONObject jsonObject2 = JSONObject.fromObject (c1,config);

        System.out .println("Class c1");

        System.out .println(jsonObject2);

    }

}

 

    【运行结果

 

Student s1

{"age":22,"sex":" ","userName":"xiapi"}

Class c1

{"date":"2012-05-21 19:19:31","name":" 计算机应用 1 ","students":[{"age":10,"sex":" ","userName":"xiapi1"},{"age":11,"sex":" ","userName":"xiapi2"},{"age":12,"sex":" ","userName":"xiapi3"}]}

 

2.6 处理XmlToJson

    在处理XML时,需要另添加"xom-1.2.8.jar "包。

    下载地址:http://www.xom.nu/

    【示例代码

 

package com.hebut.jsonlib;

 

import net.sf.json.JSON;

import net.sf.json.xml.XMLSerializer;

import org.junit.Test;

 

public class JsonLib {

   

    @Test

    public void xml2json(){

        String s="<student>

                        <name id='n1'>xiapi</name>

                        <sex class='s1'> </sex>

                        <age>20</age>

                    </student>";

        XMLSerializer x =new XMLSerializer();

        JSON json = x.read(s);

        System.out .println("XmlToJson");

        System.out .println(json.toString());

    }

}

 

    【运行结果

 

2012-5-21 19:01:03 net.sf.json.xml.XMLSerializer getType

信息 : Using default type string

XmlToJson

{"name":{"@id":"n1","#text":"xiapi"},"sex":{"@id":"s1","#text":" "},"age":"20"}

 

2.7 处理JsonToArrays

    【示例代码

 

package com.hebut.jsonlib;

 

import net.sf.ezmorph.test.ArrayAssertions;

import net.sf.json.JSONArray;

import net.sf.json.JSONSerializer;

import net.sf.json.JsonConfig;

 

import org.junit.Test;

 

public class JsonLib {

   

    @Test

    public void json2arrays(){

        String json1 = "['first','second']";

        JSONArray jsonArray1 = (JSONArray) JSONSerializer.toJSON (json1);

        JsonConfig jsonConfig = new JsonConfig();

        jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY );

        Object[] output1 = (Object[]) JSONSerializer.toJava (jsonArray1, jsonConfig);

        Object[] expected = new Object[] { "first", "second" };

        ArrayAssertions.assertEquals (expected, output1);

        System.out .println("Object[]");

        System.out .println(output1.length);

        System.out .println(output1[1]);

       

        String json2 ="[[1,2],[3,4]]";

        JSONArray jsonArray2 = JSONArray.fromObject (json2);

        Object[][] output2 = (Object[][])JSONArray.toArray (jsonArray2);

        System.out .println("Object[][]");

        System.out .println(output2.length);

        System.out .println(output2[0][0]);

    }

}

 

    【运行结果

 

Object[]

2

second

Object[][]

2

1

 

2.8 处理JsonToCollections

    【示例代码

 

package com.hebut.jsonlib;

 

import java.util.List;

import net.sf.json.JSONArray;

import net.sf.json.JSONSerializer;

import org.junit.Test;

 

public class JsonLib {

   

    @Test

    public void json2collections(){

        String json1 = "['first','second']";

        JSONArray jsonArray1 = (JSONArray) JSONSerializer.toJSON (json1);

        List output1 = (List) JSONSerializer.toJava (jsonArray1);

        System.out .println("List");

        System.out .println(output1.get(0));

       

        String json2 = "[{'age':10,'sex':' ','userName':'xiapi1'},

                        {'age':11,'sex':' ','userName':'xiapi2'}]";

        JSONArray jsonArray2 = JSONArray.fromObject (json2);

        List<Student> output2 = JSONArray.toList (jsonArray2,Student.class );

        System.out .println("List<Student>");

        System.out .println(output2.size());

        System.out .println(output2.get(0));

        System.out .println(output2.get(0).getUserName());

    }

}

 

    【运行结果

 

List

first

List<Student>

2

com.hebut.jsonlib.Student@16f144c

xiapi1

 

2.9 处理JsonToMap

    【示例代码

 

package com.hebut.jsonlib;

 

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

import net.sf.ezmorph.Morpher;

import net.sf.ezmorph.MorpherRegistry;

import net.sf.ezmorph.bean.BeanMorpher;

import net.sf.ezmorph.test.ArrayAssertions;

import net.sf.json.JSONObject;

import net.sf.json.JSONSerializer;

import net.sf.json.util.JSONUtils;

import net.sf.json.xml.XMLSerializer;

 

import org.junit.Test;

 

public class JsonLib {

 

    @Test

    public void json2map(){

        String json1 ="{'arr':['a','b'],'int':1,

                        'name':'json','bool':true}";

        JSONObject jsonObject1 = JSONObject.fromObject (json1);

        Map typeMap1 = new HashMap();

        typeMap1.put("arr", String[].class );

        typeMap1.put("int", Integer.class );

        typeMap1.put("name", String.class );

        typeMap1.put("bool", Boolean.class );

        Map output1 = (Map)JSONObject.toBean (jsonObject1, Map.class ,typeMap1);

        System.out .println("Map");

        System.out .println(output1.size());

        System.out .println(output1.get("name"));

        System.out .println(output1.get("arr"));

       

        String json2 ="{'k1':{'age':10,'sex':' ','userName':'xiapi1'},

                        'k2':{'age':12,'sex':' ','userName':'xiapi2'}}";

        JSONObject jsonObject2 = JSONObject.fromObject (json2);

        Map<String,Class<?>> typeMap2 =new HashMap<String,Class<?>>();

        Map<String,Student> output2 = (Map<String,Student>) JSONObject.toBean (jsonObject2,Map.class ,typeMap2);

        System.out .println("Map<String,Student>");

        System.out .println(output2.size());

        System.out .println(output2.get("k1"));

       

        // 先往注册器中注册变换器,需要用到 ezmorph 包中的类

    MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry ();

    Morpher dynaMorpher = new BeanMorpher(Student.class , morpherRegistry);

    morpherRegistry.registerMorpher(dynaMorpher);

 

        System.out .println(((Student)morpherRegistry.morph( Student.class ,output2.get("k2"))).getUserName());

    }

}

 

    【运行结果

 

Map

4

json

[a, b]

Map<String,Student>

2

net.sf.ezmorph.bean.MorphDynaBean@5b8827[

{sex= , age=10, userName=xiapi1}

]

xiapi2

 

2.10 处理JsonToBean

    【示例代码

 

package com.hebut.jsonlib;

 

import net.sf.ezmorph.Morpher;

import net.sf.ezmorph.MorpherRegistry;

import net.sf.ezmorph.bean.BeanMorpher;

import net.sf.ezmorph.object.DateMorpher;

import net.sf.json.JSONObject ;

import net.sf.json.JSONSerializer;

import net.sf.json.util.JSONUtils;

 

import org.junit.Test;

 

public class JsonLib {

   

    @Test

    public void json2bean(){

        // 简单对象

        String json1 = "{'age':22,'sex':' ','userName':'xiapi'}";

        JSONObject jsonObject1 = JSONObject .fromObject (json1);

        Student output1 = (Student)JSONObject .toBean (jsonObject1, Student.class );

        System.out .println("Student");

        System.out .println(output1.getUserName());

       

        // 复杂对象

        String json2 = "{'date':'2012-05-21 13:03:11',

                            'name':' 计算机应用 1 ',

                'students':[{'age':10,'sex':' ','userName':'xiapi1'},

                            {'age':11,'sex':' ','userName':'xiapi2'}]}";

        // 转为日期

        String[] DATE_FORMAT = { "yyyy-MM-dd HH:mm:ss" };

        MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry ();

        morpherRegistry.registerMorpher(new DateMorpher(DATE_FORMAT));

        JSONObject jsonObject2 = JSONObject .fromObject (json2);

        Map typeMap1 = new HashMap();

        typeMap1.put("date", Date.class );

        typeMap1.put("name",String.class );

        typeMap1.put("students", Student.class );

        Class output2 = (Class)JSONObject .toBean (jsonObject2, Class.class ,typeMap1);

        System.out .println("Class");

        System.out .println(output2.getName());

        System.out .println(output2.getDate());

        System.out .println(output2.getStudents().get(0).getUserName());

    }

}

 

    【运行结果

 

Student

xiapi

Class

计算机应用 1

Mon May 21 13:03:11 CST 2012

xiapi1

 

2.11 处理JsonToXml

    【示例代码

 

package com.hebut.jsonlib;

 

import net.sf.json.JSONObject;

import net.sf.json.xml.XMLSerializer;

import org.junit.Test;

 

public class JsonLib {

   

    @Test

    public void json2xml(){

        String json1 = "{'age':22,'sex':' ','userName':'xiapi'}";

        JSONObject jsonObj = JSONObject.fromObject (json1);

    XMLSerializer x = new XMLSerializer();

    String xml = x.write(jsonObj);

    System.out .println("XML");

    System.out .println(xml);

    }

}

 

    【运行结果

 

XML

<?xml version="1.0" encoding="UTF-8"?>

<o><age type="number">22</age><sex type="string"> </sex><userName type="string">xiapi</userName></o>

 

2.12 对象JSONArray

    【示例代码

 

package com.hebut.jsonlib;

 

import net.sf.json.JSONArray;

import org.junit.Test;

 

public class JsonLib2 {

 

    @Test

    public void testJSONArray() {

        JSONArray jsonArray = new JSONArray();

        jsonArray.add(0," 第一个值 ");

        jsonArray.add(1," 第二个值 ");

        jsonArray.add(2," 第三个值 ");

        System.out .print(jsonArray.toString());

    }

}

 

    【运行结果

 

[" 第一个值 "," 第二个值 "," 第三个值 "]

 

2.13 对象JSONObject

    【示例代码

 

package com.hebut.jsonlib;

 

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

 

import org.junit.Test;

 

public class JsonLib2 {

 

    @Test

    public void testJSONObject() {

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("name", "xiapi");

        jsonObject.put("age", 20);

        jsonObject.put("sex", " ");

        JSONArray jsonArray = new JSONArray();

        jsonArray.add(" 唱歌 ");

        jsonArray.add(" 摄影 ");

        jsonArray.add(" 象棋 ");

        jsonObject.element("hobby",jsonArray);

        System.out .println(jsonObject);

    }

}

 

    【运行结果

 

{"name":"xiapi","age":20,"sex":" ","hobby":[" 唱歌 "," 摄影 "," 象棋 "]}

 

3、日期转换

  json-lib转换出来的日期类型格式:

 

"birthday":{"date":1,"day":0,"hours":0,"minutes":0,"month":7,"nanos":0,"seconds":0,"time":1280592000000,"timezoneOffset":-480,"year":110}

 

  那么我们如果想要"yyyy-MM-dd HH:mm:ss "这种格式的怎么办呢?

3.1 三种解决方案

  都必须使用jsonConfig对象进行处理

  (1)使用jsonConfig的setExcludes的方法进行过滤,将所需要过滤的字段名传入setExcludes方法。

 

    public void objectToJson(){

        //创建对象

        Emp emp= new Emp(****);

        //创建jsonConfig对象

        JsonConfig config=new JsonConfig();

        //设置过滤字段

        config.setExcludes(new String[]{"dept"});

        String s=JSONObject.fromObject(emp,config).toString();

        System.out.println(s);

    }

 

  (2)使用jsonConfig的setJsonPropertyFilter进行属性过滤,过滤器中返回true表示过滤该字段,返回false表示可以转换该字段。

 

    public void objectToJson(){

        //创建对象

        Emp emp= new Emp(****);

        //创建jsonConfig对象

        JsonConfig config=new JsonConfig();

        //设置过滤字段

        config.setJsonPropertyFilter(new PropertyFilter() {

            public boolean apply(Object arg0, String arg1, Object arg2) {

                if("dept".equals(arg1)){

                    return true;

                }

                return false;

            }

        });

        String s=JSONObject.fromObject(emp,config).toString();

        System.out.println(s);

    }

 

  上述两种解决方案可以解决部分问题,但是json-lib使用代理进行反射,所以如果想要部门表的信息,而去过滤部门表的员工对象,这样还是解决不了。这样可以使用更简单有效的方案

 

  (3)使用jsonConfig的setCycleDetectionStrategy()方法进行忽略死循环。

         使用jsonConfig的registerJsonValueProcessor()进行属性转换设置。

 

    public void objectToJson(){

        //创建对象

        Emp emp= new Emp(****);

        //创建jsonConfig对象

        JsonConfig config=new JsonConfig();

        //设置循环策略为忽略 解决json最头疼的问题 死循环

        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

        //设置 json转换的处理器 用来处理日期类型

        //凡是反序列化Date类型的对象,都会经过该处理器进行处理

        config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {

            //参数1 :属性名 参数2:json对象的值 参数3:jsonConfig对象

            public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {

                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Date d=(Date) arg1;

                return sdf.format(d);

            }

            public Object processArrayValue(Object arg0, JsonConfig arg1) {

                return null;

            }

        });

        String s=JSONObject.fromObject(emp,config).toString();

        System.out.println(s);

    }

 

  这种方案可以解决死循环问题和日期格式化的问题。

  结果:

 

{"birthday":"2010-08-01 00:00:00","dept":{"depid":1,"depname":"开发部","emps": [{"birthday":"2009-08-01 00:00:00","dept":null,"empid":30,"empname":"田 七"},null]},"empid":27,"empname":"王五"}

 

3.2 封装函数方案

 

public static String convert2Json2(Object object) {

    JsonConfig jsonConfig = new JsonConfig();

    jsonConfig.registerJsonValueProcessor(java.util.Date.class,

            new JsonValueProcessor() {

                private final String format = "yyyy-MM-dd hh:mm:ss";

 

                public Object processArrayValue(Object object,

                        JsonConfig jsonConfig) {

                    return null;

                }

 

                public Object processObjectValue(String string,

                        Object object, JsonConfig jsonConfig) {

                    if (null == object) {

                        return "";

                    } else {

                        if (object instanceof java.util.Date) {

                            SimpleDateFormat simpleDateFormat = new

                                SimpleDateFormat(format);

                            String dateStr = simpleDateFormat

                                    .format(object);

                            return dateStr;

                        }

                    }

 

                    return object.toString();

                }

            });

 

    if (object instanceof String)

        return object.toString();

    if ((object instanceof Object[]) || (object instanceof List)) {

        JSONArray jsonObject = JSONArray.fromObject (object, jsonConfig);

        return jsonObject.toString() + '\n';

    } else {

        JSONObject jsonObject = JSONObject.fromObject (object, jsonConfig);

        return jsonObject.toString() + '\n';

    }

}

你可能感兴趣的:(json-lib)