如何使用Java json-simple库读取打印JSON数组元素并解决类型转换报错
问题解决方案
错误根因
你遇到的ClassCastException是因为AccountCreditrisk对应的JSON数组中存储的元素是JSONObject类型,而非String类型,你在声明迭代器时错误指定了泛型为String,还对取出的元素做了强制String转换,触发了类转换异常。
修改方案
你只需要调整数组迭代部分的代码,将取出的元素先转为JSONObject类型,既可以直接打印整个对象内容,也可以单独获取对象内部的字段值。
修改后的完整代码
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[]) { //创建JSONParser对象 JSONParser jsonParser = new JSONParser(); try { //解析JSON文件内容,注意Windows路径下反斜杠需要转义,写为\\ JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("C:\\json\\CredirRisk_corainputtoIIB.json")); 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")); //获取数组 JSONArray jsonArray = (JSONArray) jsonObject.get("AccountCreditrisk"); System.out.println(""); System.out.println("AccountCreditrisk details: "); //调整迭代器泛型为JSONObject Iterator<JSONObject> iterator = jsonArray.iterator(); int index = 0; while(iterator.hasNext()) { JSONObject riskObj = iterator.next(); System.out.println("=== 第"+(++index)+"条风险数据 ==="); // 可以直接打印整个对象 System.out.println(riskObj.toString()); // 也可以单独取内部字段 System.out.println("risk_code: "+ riskObj.get("risk_code")); System.out.println("op_code: "+ riskObj.get("op_code")); System.out.println("credit_analyst: "+ riskObj.get("credit_analyst")); System.out.println("account_key: "+ riskObj.get("account_key")); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } }
其他注意事项
Java字符串中表示Windows路径的反斜杠\需要转义为\\,否则会被识别为转义字符导致路径读取错误。
内容的提问来源于stack exchange,提问作者Raja Praveen Katta
相关产品推荐
相关产品推荐

