解析json字串,並且獲取其中某個key的值
阿新 • • 發佈:2019-02-17
<span style="font-size:18px;">public static void main(String[] args) { String findStr = "hobby,listening,chinese";//查詢json字串中的某個key的值,定義查詢目錄的順序 String str = "{\"person\": {\"name\": \"jack\"},\"hobby\": {\"listening\": [{\"chinese\": \"1\",\"japanese\": \"2\"}],\"age\": \"18\"}}"; // String str = "{\"person\": {\"name\": \"jack\"},\"hobby\": {\"listening\": {\"chinese\": \"1\",\"japanese\": \"2\"},\"age\": \"18\"}}"; // String findStr = "listening,chinese";//查詢json字串中的某個key的值,定義目錄 // String str = "{\"listening\": {\"chinese\": \"1\",\"japanese\": \"2\"},\"age\": \"18\"}"; // String str = "{\"listening\": [{\"chinese\": \"1\",\"japanese\": \"2\"}],\"age\": \"18\"}"; String arr[] = findStr.split(","); String st =null; JSONObject jsonObject = JSONObject.parseObject(str); for (int i = 0; i < arr.length-1; i++) { if (jsonObject.get(arr[i]) instanceof JSONArray){ JSONArray jsonArray = (JSONArray) jsonObject.get(arr[i]); jsonObject = (JSONObject) jsonArray.get(0); } else { jsonObject = (JSONObject) jsonObject.get(arr[i]); } continue; } st = (String) jsonObject.get(arr[arr.length-1]); System.out.println(st); }</span>