`
liuhd2010
  • 浏览: 145951 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

JSON学习

 
阅读更多

一、JSON的全称是JavaScript Object Notation,是一种轻量级的数据交换格式。

二、通过java来创建JSON对象

1.引入jar包
我这里使用的是json-lib-2.3-jdk15.jar,下载地址:http://sourceforge.net/projects/json-lib/files/
Json-lib requires (at least) the following dependencies in your classpath:
    jakarta commons-lang 2.4
    jakarta commons-beanutils 1.7.0
    jakarta commons-collections 3.2
    jakarta commons-logging 1.1.1 
    ezmorph 1.0.6

2.重要的对象及方法
    1)JSONObject:JSON对象{}。
    2)JSONArray:JSON数组对象,[{},{}]。
    3)fromObject(object):将对象转换为JSON对象。
    4)JSONObject.accumulate(key,value):向JSONObject中增加JSON数据,可以重复。
    5)element(key,value):向JSON对象中增加JSON数据,如果重复后一个会替换前一个。
    6)toString(i,i):将JSON对象转换为字符串,如果包含参数,是将其美化后输出。

 /**
   * 描述 : <将字符串或数组转换为JSON>. <br>
   */
JSONObject resultJSON = new JSONObject();
resultJSON
		.accumulate("name", "Violet")
		.accumulate("occupation", "developer")
		.accumulate("age", new Integer(22))
		.accumulate("array", new int[] { 1, 2, 3 })
		.accumulate(
				"muliArray",
				"[{'type': '你好', 'value': 'kelly@seankelly.biz'},{'type': 'home', 'pref': 1, 'value': 'kelly@seankelly.tv'}]");
System.out.println(resultJSON.toString(1, 1));

/**
 * 描述 : <将Map转换为JSON>. <br>
 */
JSONObject resultJSON2 = null;
Map map = new HashMap(15);
map.put("name", "hanqf");
map.put("age", 28);
map.put("phone", "{home:135,busi:139}");
resultJSON2 = JSONObject.fromObject(map);
System.out.println(resultJSON2.toString());

/**
 * 描述 : <JavaBean转换为JSON>. <br>
 */
JSONObject resultJSON3 = null;
People people = new People();
Phone phone = new Phone("135", "138");
people.setPhone(phone);
resultJSON3 = JSONObject.fromObject(people);
System.out.println(resultJSON3.toString());

/**
 * 描述 : <List转换为JSON>. <br>
 */
JSONArray jsonArray = null;
People people2 = null;
Phone phone2 = null;
List<People> pList = new ArrayList<People>();
for (int i = 0; i < 3; i++) {
	people2 = new People();
	phone2 = new Phone("135" + i, "138" + i);
	people2.setAge(i);
	people2.setPhone(phone2);
	pList.add(people2);
}
jsonArray = JSONArray.fromObject(pList);
System.out.println(jsonArray.toString());

 三、JSON进阶

1.再来看几个重要的对象和方法
     1)JSON:JSON对象的顶级接口,JSONObject,JSONArray都实现了该接口
     2)JSONSerializer:JSON串行化对象
     3)JSONSerializer.toJSON(object):将对象串行化为JSON
     4)JSONSerializer.toJava(json):将JSON转换为对象
     5)MorphDynaBean:JSONSerializer.toJava(json)后的值默认为MorphDynaBean
     6)XMLSerializer:JSON转换为xml对象
     7)xMLSerializer.write(json):将JSON对象转换为xml
     8)xMLSerializer.read(xml):将xml转换为JSON对象

2.实例

// json转map
System.out.println("Line 7:");
Map mapp = (Map) JSONObject.toBean(resultJSON2, Map.class);
System.out.println(mapp.get("name"));

// json转JavaBean
System.out.println("Line 8:");
People pp = (People) JSONObject.toBean(resultJSON3, People.class);
System.out.println(pp.getPhone().getBusi());

  

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics