登录 / 注册
json字符串转换为JSONObject和JSONArray
发布时间:2017-08-30 10:26:40 查看:2411
importorg.json.JSONArray;
importorg.json.JSONObject;
 
 
publicclassJSONTest{
   publicstaticvoidmain(String[] args){
      //JSONObject
      String jsonMessage ="{\"语文\":\"88\",\"数学\":\"78\",\"计算机\":\"99\"}";
      String value1 =null;
      try{
           //将字符串转换成jsonObject对象
          JSONObject myJsonObject =newJSONObject(jsonMessage);
          //获取对应的值
          value1 = myJsonObject.getString("数学");
     }catch(JSONException e){
          System.out.println("异常");
      }
      System.out.println("value1="+value1);
 
 
       //JSONArray
    jsonMessage ="[{'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 =newJSONArray(jsonMessage);
              for(inti=0; i < myJsonArray.length() ;i++) {
               //获取每一个JsonObject对象
               JSONObject myjObject = myJsonArray.getJSONObject(i);
     
                //获取每一个对象中的值
                 String numString = myjObject.getString("num");
                 intenglishScore = myjObject.getInt("外语");
                 inthistoryScore = myjObject.getInt("历史");
                 intgeographyScore = 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){
                    System.out.println("异常");
           }
 
     }
}
宁夏银川舜新艺软件开发
ShunXinyi Soft develop
主要经营
软件开发,网站制作,网页设计,移动应用(安卓、苹果),微信,微网站,
FLASH动画,电子商务,计算机软硬件及网络设备等。
电话:18695132945 QQ:23923027
舜新艺软件开发 宁ICP备16001093号-1 宁公网安备 64010602000809号