生活随笔
收集整理的這篇文章主要介紹了
解析json串
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
????使用java進行網(wǎng)頁抓取時,有時會直接獲取到json串,json串要獲取的數(shù)據(jù)嵌套復雜,這里自己寫一個遞歸的方式進行解析指定名稱的數(shù)據(jù),進行記錄,以便日后復用。
????原有json串:
{"total":?3,"class":?"二年級","members":?[{"age":?18,"name":?"張三","course":[{"Chinese":"123","Maths":"121","English":"110"}]},?{"age":?19,"name":?"李四","course":[{"Chinese":"118","Maths":"129","English":"130"}]},?{"age":?18,"name":?"王麻子","course":[{"Chinese":"133","Maths":"111","English":"134"}]}]
}
????java遞歸解析方法:
import?org.json.JSONObject;
import?org.json.JSONArray;/***?*?@param?returnObject?返回的數(shù)據(jù)List*?@param?object?傳入的json串*?@param?keys?需要解析的節(jié)點數(shù)組,按順序組成數(shù)組*?@param?index?index==keys.length為基線條件,index起始為0*/
private?static?void?getData(List<Object>?returnObject,Object?object,String[]?keys,int?index){if?(index==keys.length){returnObject.add(object);return;}if?(object?instanceof?JSONObject){if?(!((JSONObject)?object).has(keys[index])){return?;}Object?object1=((JSONObject)?object).get(keys[index]);getData(returnObject,object1,keys,index+1);}?else?if?(object?instanceof?JSONArray){JSONArray?jsonArray=(JSONArray)?object;for?(Object?jsonObject:jsonArray){getData(returnObject,jsonObject,keys,index);}}
}
????遞歸調(diào)用方法:
public?static?void?main(String[]?args)?{String?jsonStr="{\n"?+"\t\"total\":?3,\n"?+"\t\"class\":?\"二年級\",\n"?+"\t\"members\":?[{\n"?+"\t\t\"age\":?18,\n"?+"\t\t\"name\":?\"張三\",\n"?+"\t\t\"course\":[{\n"?+"\t\t\t\"Chinese\":\"123\",\n"?+"\t\t??\t\"Maths\":\"121\",\n"?+"\t\t??\t\"English\":\"110\"\n"?+"\t\t}]\n"?+"\t},?{\n"?+"\t\t\"age\":?19,\n"?+"\t\t\"name\":?\"李四\",\n"?+"\t\t\"course\":[{\n"?+"\t\t\t\"Chinese\":\"118\",\n"?+"\t\t??\t\"Maths\":\"129\",\n"?+"\t\t??\t\"English\":\"130\"\n"?+"\t\t}]\n"?+"\t},?{\n"?+"\t\t\"age\":?18,\n"?+"\t\t\"name\":?\"王麻子\",\n"?+"\t\t\"course\":[{\n"?+"\t\t\t\"Chinese\":\"133\",\n"?+"\t\t??\t\"Maths\":\"111\",\n"?+"\t\t??\t\"English\":\"134\"\n"?+"\t\t}]\n"?+"\t}]\n"?+"}";List<Object>?returnObject=new?ArrayList<>();getData(returnObject,new?JSONObject(jsonStr),"members,course".split(","),0);System.out.println(returnObject);returnObject=new?ArrayList<>();getData(returnObject,new?JSONObject(jsonStr),"members,course,Chinese".split(","),0);System.out.println(returnObject);
}
輸出結(jié)果:
[[{"Maths":"121","English":"110","Chinese":"123"}],?[{"Maths":"129","English":"130","Chinese":"118"}],?[{"Maths":"111","English":"134","Chinese":"133"}]]
[123,?118,?133]
轉(zhuǎn)載于:https://blog.51cto.com/zuohao1990/2295757
總結(jié)
以上是生活随笔為你收集整理的解析json串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。