日期:2014-05-16  浏览次数:20439 次

JSON的基本用法
    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写,同时也易于机器解析和生成。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。
    笔者使用JSON技术,主要在AJAX中.使用的是jQuery框架.请求完后台数据,返回JSON格式的数据,由js处理.
下面是2个常用的框架和代码,笔者这里不做过多的说明.
1)json_jackson
package test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Test {

	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		User user = new User();
		user.setName("phl");
		user.setAge(25);
		User user2 = new User();
		user2.setName("luckybird");
		user2.setAge(26);
		
		List<User> list = new ArrayList<User>();
		list.add(user);
		list.add(user2);
		System.out.println(mapper.writeValueAsString(list));
	}
}

2)json-lib
package test;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

public class Test {

	public static void main(String[] args) throws Exception {
		User user = new User();
		user.setName("phl");
		user.setAge(25);
		User user2 = new User();
		user2.setName("luckybird");
		user2.setAge(26);

		List<User> list = new ArrayList<User>();
		list.add(user);
		list.add(user2);

		JSONObject json = JSONObject.fromObject(user);
		System.out.println(json.toString());

		// ********************************************************
		JSON json2 = JSONSerializer.toJSON(list);
		System.out.println(json2.toString());

		json2 = JSONSerializer.toJSON(new User());
		System.out.println(json2.toString());

	}
}