Transforming beans, maps, collections, java arrays and XML to JSON

  java将对象、数组、集合和map与json数据间的转换

几款常用JSON类库

Jackson:http://jackson.codehaus.org/  (性能最好)

JSON-lib:http://json-lib.sourceforge.net/

Gson:http://code.google.com/p/google-gson/

一、使用JSON-lib

package com.zot.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/*
 * json-lib
 * Java library for transforming beans, maps, collections, java arrays and XML to JSON.
 */

public class TestToJson {
    public static void main(String[] args) {
        //ArraysOrListToJson();
        MapsToJson();
        //System.out.println("hello");
    }
    
    //当是对象的时候 
    public static void ObjectToJson() {
        Student student = new Student();
        student.setAge(18);
        student.setName("zhangsan");
        student.setSex("male");
        JSONObject jsonObject = JSONObject.fromObject(student);
        System.out.println(jsonObject);
    }

    //当是数组或list的时候 
    public static void ArraysOrListToJson() {
        Student[] stus = new Student[5];
        List<Student> stuList = new ArrayList<Student>();
        for (int i = 0; i < stus.length; i++) {
            stus[i] = new Student();
            stus[i].setAge(i * 10 + 8);
            stus[i].setName("zhang" + i);
            stus[i].setSex("male");
            // 添加到list,一会儿用
            stuList.add(stus[i]);
        }
        JSONArray jsonArray = JSONArray.fromObject(stus); 
        //JSONArray jsonArray = JSONArray.fromObject(stuList); 
        System.out.println(jsonArray);//和下面打印的结果相同 
    }
    
    //当既有对象又有数组的时候 
    public static void MapsToJson(){
        Map<String,Object> map = new HashMap<String,Object>(); 
        Teacher teacher = new Teacher(); 
        teacher.setAge(30); 
        teacher.setName("laoshi"); 
        teacher.setSex("male"); 
        
        Student[] stus = new Student[5];
        List<Student> stuList = new ArrayList<Student>();
        for (int i = 0; i < stus.length; i++) {
            stus[i] = new Student();
            stus[i].setAge(i * 10 + 8);
            stus[i].setName("zhang" + i);
            stus[i].setSex("male");
            // 添加到list,一会儿用
            stuList.add(stus[i]);
        }
        
    //    map.put("teacher", teacher); 
        map.put("student", stuList); 
        JSONObject jsonObjectFromMap = JSONObject.fromObject(map); 
        System.out.println(jsonObjectFromMap); 
    }

}

  需要引入json lib包:

maven pom.xml中加入:

(注意需要:json的jar的名称中多了一个跟JDK相关的名称,例如jdk15,它表示在相同版本下针对不同的环境或者jdk使用的jar,如何单纯用maven的坐标去访问这个jar是访问不到的。需要添加一个新的标签classifier,这会将这个元素名在加在最后来查找相应的jar

    <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

 

二、使用Jackson

 

posted on 2014-03-28 13:29  Galloper  阅读(231)  评论(0编辑  收藏  举报

导航