json文字列をJSOnObjectとJSOnArrayに変換

2785 ワード

import org.json.JSONArray;
import org.json.JSONObject;


public class JSONTest{
   public static void main(String[] args){
      //JSONObject
      String jsonMessage = "{\" \":\"88\",\" \":\"78\",\" \":\"99\"}";
      String value1 = null;
      try{
           // jsonObject 
          JSONObject myJsonObject = new JSONObject(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 = 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){
                    System.out.println(" ");
           }

     }
}