當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Java用JSONObject-lib来解析json串
生活随笔
收集整理的這篇文章主要介紹了
Java用JSONObject-lib来解析json串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
直接貼代碼:(所需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) {String jsonStr = json.toString();if(this.isString(jsonStr)){list.add(jsonStr);}if(this.isJson(jsonStr)){list.add(this.testJson(jsonStr.toString()));}if(this.isJsonArray(jsonStr)){list.add(this.testJsonArray(jsonStr.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();}}
?
轉載于:https://www.cnblogs.com/zhangfei/p/3992550.html
總結
以上是生活随笔為你收集整理的Java用JSONObject-lib来解析json串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle中简单查询语句的格式及执行顺
- 下一篇: JavaScript实现http地址自动