Java、Json转换方式之一:json-lib

 

json-lib能把Java对象转换为Json,也可以把Json字符串转换为Java对象。

准备工作:

  下载jar包:http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/

  本例使用2.3版本,也可以使用2.4版本。

  依赖包(都是Apache下的开源项目包):  

    jakarta commons-lang 2.5

    jakarta commons-beanutils 1.8.0

    jakarta commons-collections 3.2.1

    jakarta commons-logging 1.1.1 

  要使用的JavaBean:Student类  

public class Student {

    private int id;

    private String name;

    private String email;

    private String address;

    private Birthday birthday;



    public String toString() {

        return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;

    }

}

  和Birthday类:  

public class Birthday {

    private String birthday;



    public Birthday(String birthday) {

        super();

        this.birthday = birthday;

    }



    public Birthday() {

    }



    @Override

    public String toString() {

        return this.birthday;

    }

}

  

开始进行解析和转换:

  建立测试类,并在init()中初始化数据,destory()中销毁数据:

public class JsonTest {

    private JSONArray jsonArray = null;

    private JSONObject jsonObject = null;

    private Student student = null;

    private String json = "{\"address\":\"beijing\",\"age\":21,\"birthday\":{\"birthday\":\"2012-12-12\"},\"email\":\"[email protected]\",\"name\":\"liheng\"}";



    private void init() {

        jsonArray = new JSONArray();

        jsonObject = new JSONObject();

        student = new Student() {

            {

                setAddress("beijing");

                setAge(21);

                setEmail("[email protected]");

                setName("liheng");

                setBirthday(new Birthday("2012-12-12"));

            }

        };

    }



    public void destory() {

        jsonArray = null;

        jsonObject = null;

        student = null;

        System.gc();

    }

}

  

  接下来的工作,就是在JsonTest中建立各个方法,然后测试并输出。我这里总结了JavaBean到Json的各种转换方式,贴出来以供参考:

    /**

     * 将java对象转换为json字符串:三种方式

     * JSONObject和JSONSerializer返回的一样。大致为:{"name":"n","age":12}

     * JSONArray为:[{"name":"n","age":12}]

     */

    public void javaToJson() {

        JSONObject.fromObject(student).toString();

        JSONArray.fromObject(student).toString();

        JSONSerializer.toJSON(student).toString();

    }



    /**

     * list转换为json。对于集合,只能使用JSONArray和JSONSerializer

     * 返回的结果大致:[{"name":"n","age":12},{"name":"n","age":12}]

     */

    public void listToJson() {

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

        list.add(student);

        list.add(student);

        System.out.println(JSONArray.fromObject(list));

        System.out.println(JSONSerializer.toJSON(list));

    }



    /**

     * map转换为json。对于function()则不加引号,按照js的规则

     */

    public void mapToJson() {

        Map<String, Object> map = new HashMap<String, Object>();

        map.put("A", student);

        student.setName("jack");

        map.put("B", student);

        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]; }");



        System.out.println(JSONObject.fromObject(map));

        System.out.println(JSONArray.fromObject(map));

        System.out.println(JSONSerializer.toJSON(map));

    }



    /**

     * 更多的类型转换为json,参考上面

     */



    /**

     * json字符串转换为Java对象

     */

    public void jsonToJava() {

        json = "{\"address\":\"beijing\",\"age\":21,\"birthday\":{\"birthday\":\"2012-12-12\"},\"email\":\"[email protected]\",\"name\":\"liheng\"}";

        jsonObject = JSONObject.fromObject(json);

        Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);

        stu = (Student) JSONSerializer.toJava(JSONSerializer.toJSON(json));

    }



    /**

     * 将json转换为数组,使用JSONArray.toArray(): 1、jsonArray =

     * JSONArray.fromObject(json); 2、Object[] os = jsonArray.toArray();

     * 

     * 将json转换为list,使用JSONArray.toList(): 1、jsonArray =

     * JSONArray.fromObject(json); 2、List<Student> list =

     * JSONArray.toList(jsonArray, Student.class);

     *  上面转换为List的方法已经过时。使用下面的方法:

     *          1、jsonArray = JSONArray.fromObject(json);

     *        2、JSONArray.toList(jsonArray, new Person(), new JsonConfig());//参数1为要转换的JSONArray数据,参数2为要转换的目标数据,即List盛装的数据

     * 

     * 将json转换为map,较为麻烦,但也不常用;

     *      json = "{\"arr\":[\"a\",\"b\"],\"A\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"

                + "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"int\":1,"

                + "\"B\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"

                + "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"name\":\"json\",\"bool\":true}";

            jsonObject = JSONObject.fromObject(json);

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

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

            clazzMap.put("A", Student.class);

            clazzMap.put("B", Student.class);

            Map<String, ?> mapBean = (Map) JSONObject.toBean(jsonObject, Map.class, clazzMap);

            System.out.println(mapBean);

    

            Set<String> set = mapBean.keySet();

            Iterator<String> iter = set.iterator();

            while (iter.hasNext()) {

                String key = iter.next();

                fail(key + ":" + mapBean.get(key).toString());

            }

     * 

     */

  最后,可以在main()方法中进行测试:  

    public static void main(String[] args) {

        JsonTest t = new JsonTest();

        t.init();

        t.mapToJson();        

    }

 

自我思考:json-lib解析方式比较保守,估计是使用Java反射和字符串拆解来进行的解析。解析速度一般,使用简洁性一般。

 

下面介绍JavaBean转换Json的另一种方式,也是Spring MVC内置使用的解析方式:Jackson。

 

 

 

 

 

 

  

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