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\”:\”li150@163.com\”,\”name\”:\”liheng\”}”;

private void init() {
    jsonArray = new JSONArray();
    jsonObject = new JSONObject();
    student = new Student() {
        {
            setAddress("beijing");
            setAge(21);
            setEmail("li150@163.com");
            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\":\"li150@163.com\",\"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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值