java - 解析 JSON 时如何替换 System.out.println 作为返回?

标签 java arrays json for-loop return

 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,返回句子等返回变量。如何做到这一点?

最佳答案

创建一个对象。使用数组列表来存储您的对象并在以后使用它。

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();
 }
}

关于java - 解析 JSON 时如何替换 System.out.println 作为返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40077644/

相关文章:

Java SSL 重新协商(从 SSL 到清除 channel )

arrays - 连续数组

python - 在Python 3上使用 `json.dumps`时如何添加一些空行?

java - Jackson 意外字符 ('h'(代码 104)) : expected a valid value

java - Tomcat 404 : The requested resource is not available

java - Android Studio 重命名原生库

c++ - 在 C++ 中将整数数组作为参数传递?

javascript - 根据用户从 JSON 文件中选择的月份显示图表

java - 无法在服务器部署上启动 Quartz

perl - 当您尝试使用 Perl 打印数组或散列并得到 Array(0xd3888) 时,这意味着什么?