当前位置: 代码迷 >> JavaScript >> 字符串变换为json对象
  详细解决方案

字符串变换为json对象

热度:112   发布时间:2012-10-25 10:58:58.0
字符串转换为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"));
		}

	}

}
?
  相关解决方案