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

字符串转换为json对象

把字符串转换为json对象

import java.io.BufferedReader;
import java.io.FileReader;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestJson {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//读取文件内容
		String filePath = "c:/json/2222.txt";
		StringBuffer sb = new StringBuffer();
		try {
			FileReader read = new FileReader(filePath);
			BufferedReader br = new BufferedReader(read);

			String row = "";
			while ((row = br.readLine()) != null) {
				sb.append(row);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		String jsonString = sb.toString();
		//内容为[{"id":110000,"text":"北京"},{	"id":120000,"text":"天津"},{	"id":310000,"text":"上海"}]
		System.out.println(jsonString);
		//开始进行转换
		JSONArray array = JSONArray.fromObject(jsonString);
		for (int i = 0; i < array.size(); i++) {
			JSONObject jvo = (JSONObject) array.getJSONObject(i);
			System.out.println(jvo.getString("id")+"       "+jvo.getString("text"));
		}

	}

}
?