JSON字串轉換JSONObject和JSONArray的方法,jsonjsonobject
一.下載json 具體到http://www.json.org/上找Java-json下載,並把其放到項目原始碼中,這樣就可以引用其類對象了
二.具體轉化過程
//JSONObjectString jsonMessage = "{\"語文\":\"88\",\"數學\":\"78\",\"電腦\":\"99\"}";String value1 = null;try{//將字串轉換成jsonObject對象JSONObject myJsonObject = new JSONObject(jsonMessage);//擷取對應的值value1 = myJsonObject.getString("數學");}catch (JSONException e){}System.out.println("value1="+value1);//JSONArrayjsonMessage = "[{'num':'成績', '外語':88, '曆史':65, '地理':99, 'object':{'aaa':'1111','bbb':'2222','cccc':'3333'}}," +"{'num':'興趣', '外語':28, '曆史':45, '地理':19, 'object':{'aaa':'11a11','bbb':'2222','cccc':'3333'}}," +"{'num':'愛好', '外語':48, '曆史':62, '地理':39, 'object':{'aaa':'11c11','bbb':'2222','cccc':'3333'}}]";JSONArray myJsonArray;try{myJsonArray = new JSONArray(jsonMessage);for(int i=0 ; i < myJsonArray.length() ;i++){//擷取每一個JsonObject對象JSONObject myjObject = myJsonArray.getJSONObject(i);//擷取每一個對象中的值String numString = myjObject.getString("num");int englishScore = myjObject.getInt("外語");int historyScore = myjObject.getInt("曆史");int geographyScore = myjObject.getInt("地理");//擷取數組中對象的對象JSONObject myjObject2 = myjObject.getJSONObject("object");String aaaString = myjObject2.getString("aaa");System.out.println("aaaString="+aaaString);System.out.println("numString="+numString);System.out.println("englishScore="+englishScore);System.out.println("historyScore="+historyScore);System.out.println("geographyScore="+geographyScore);}}catch (JSONException e){}
以上內容是小編給大家介紹的JSON字串轉換JSONObject和JSONArray的方法,希望能夠協助到大家,如果大家有疑問歡迎給我留言,小編會及時回複大家,在此也非常感謝大家對幫客之家網站的支援!