首页 > 解决方案 > 如何读取和打印 JSON 数组元素

问题描述

我正在尝试通过下面的 java 程序读取 Json 对象和数组

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class App {
   public static void main(String args[]) {
      //Creating a JSONParser object
      JSONParser jsonParser = new JSONParser();
      try {
         //Parsing the contents of the JSON file
         JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("C:\\json\\CredirRisk_corainputtoIIB.json"));
         //Forming URL
         System.out.println("Contents of the JSON are: ");
         System.out.println("Target: "+jsonObject.get("target"));
         System.out.println("Source: "+jsonObject.get("source"));
         System.out.println("Request Tracker Id: "+jsonObject.get("request_tracker_id"));
         System.out.println("Request Date And Timestamp: "+ jsonObject.get("request_datetimestamp"));
        // System.out.println("Place of birth: "+ jsonObject.get("Place_Of_Birth"));
        // System.out.println("Salary: "+jsonObject.get("Salary"));
         //Retrieving the array
         JSONArray jsonArray = (JSONArray) jsonObject.get("AccountCreditrisk");
         System.out.println("");
         System.out.println("AccountCreditrisk details: ");
         //Iterating the contents of the array
         Iterator<String> iterator = jsonArray.iterator();
         while(iterator.hasNext()) {
            System.out.println((String)iterator.next());
         }
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
            e.printStackTrace();
      } catch (ParseException e) {
            e.printStackTrace();
      }
   }
}

当我尝试执行上述 java 程序时,我得到如下输出:

JSON 的内容是: 目标:SUS 来源:CORA 请求跟踪器 ID:201013051429 请求日期和时间戳:2020-10-13 05:14:29

AccountCreditrisk 详细信息:线程“main”中的异常 java.lang.ClassCastException:org.json.simple.JSONObject 无法在 com.techwave.reusejson.App.main(App.java:33) 处转换​​为 java.lang.String

它无法读取 AccountCreditrisk 数组元素。你能帮我解决这个问题吗?

原始JSON文件如下:

{
    "target": "SUS",
    "source": "CORA",
    "request_tracker_id": "201013051429",
    "request_datetimestamp": "2020-10-13 05:14:29",
    "AccountCreditrisk": [{
        "risk_code": null,
        "payment_terms": null,
        "op_code": "056",
        "global_collector": null,
        "credit_analyst": "CRDAB000",
        "account_key": "USBL056155266B"
    }]
}

标签: json

解决方案


数组的元素不是字符串;它们是属性为字符串的 JSON 对象。您已经知道如何获取 JSON 对象的各个元素。


推荐阅读