码迷,mamicode.com
首页 > 编程语言 > 详细

Java用JSONObject-lib来解析json串

时间:2014-09-25 15:25:49      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:blog   io   os   java   ar   for   div   sp   on   

直接贴代码:(所需jar包:json-lib.jar,可能会关联一些其它的jar包,请自行搜索.)

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonParser {

	@SuppressWarnings("rawtypes")
	public void test() {		
		Map m = this.testJson("jsonString");
		System.out.println(((Map) ((List) m.get("test")).get(0)).get("test_title"));
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map testJson(String str) {
		JSONObject json = JSONObject.fromObject(str);
		Iterator<?> it = json.keySet().iterator();
		Map map = new HashMap();
		while (it.hasNext()) {
			String key = (String) it.next();
			String value = json.getString(key);
			if (this.isString(value)) {
				map.put(key, value);
			}
			if (this.isJson(value)) {
				map.put(key, this.testJson(value));
			}
			if (this.isJsonArray(value)) {
				map.put(key, this.testJsonArray(value));
			}

		}
		return map;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List testJsonArray(String str) {
		JSONArray jsonArr = JSONArray.fromObject(str);
		List list = new ArrayList();
		for (Object json : jsonArr) {
			list.add(this.testJson(json.toString()));
		}
		return list;
	}

	public boolean isJson(String s) {
		boolean flag = true;
		try {
			JSONObject.fromObject(s);
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	public boolean isJsonArray(String s) {
		boolean flag = true;
		try {
			JSONArray.fromObject(s);
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	public boolean isString(String s) {
		return !this.isJson(s) && !this.isJsonArray(s);
	}

	public static void main(String[] args) {
		JsonParser tj = new JsonParser();
		tj.test();

	}

}

 

Java用JSONObject-lib来解析json串

标签:blog   io   os   java   ar   for   div   sp   on   

原文地址:http://www.cnblogs.com/zhangfei/p/3992550.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!