String jsonString = readJsonFile(filePath);

            try {
                JSONObject jsonObject = new JSONObject(jsonString);
         JSONArray result = jsonObject.getJSONArray("result");

         for (int i =0; i < result.length(); i++){
             JSONObject j = result.getJSONObject(i);
             String s = j.getString("sentence");
             int id = j.getInt("id");
             String txtFile = j.getString("txtfile");
             System.out.println("Sentence is:: " + s);
             System.out.println("Id is:: " + id);
             System.out.println("text file is:: " + txtFile);

         }
     } catch (JSONException e) {
         e.printStackTrace();
     }


目前,以上代码能够打印出所有记录。但是,我想将system.out.println更改为返回变量,例如返回ID,返回txtFile,返回句子。怎么做?

最佳答案

创建一个对象。使用arraylist存储对象并在以后使用。

public class myItem{
   String sentence;
   int id;
   String txtfile;

   public myItem(){
   }

   public String getSentence(){
       return sentence;
   }
   public setSentence(String s){
      this.sentence = sentence;
   }
}


public void yourFunction(){
   try {
       ArrayList <myItem> myList = new ArrayList();

     JSONObject jsonObject = new JSONObject(jsonString);
     JSONArray result = jsonObject.getJSONArray("result");

     for (int i =0; i < result.length(); i++){
         JSONObject j = result.getJSONObject(i);
         String s = j.getString("sentence");

         myItem newItem = new myItem();
         newItem.setSentence(s);

         myList.add(newItem);

     }
 } catch (JSONException e) {
     e.printStackTrace();
 }
}

09-29 22:32