尝试从json文件读取文件内容时出错

时间:2018-03-08 06:11:59

标签: java json

问:我正在尝试捕获在键“值”内捕获的值并将其显示在控制台上。但是当执行错误时“org.json.simple.JSONArray无法强制转换为org.json.simple.JSONObject”

代码编写:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class FileExtractJSON 
    {
        public static void main(String[] args) throws Exception 
        {
            JSONParser parser = new JSONParser();
            try 
            {
                System.out.println("Reading JSON file from Java program");
                FileReader fileReader = new FileReader("C:\\Users\\shisyadav\\Desktop\\HP Remainco\\JSON Objects\\directkafkaconsumer_actual.json");
                JSONObject value_expected = (JSONObject) parser.parse(fileReader);
                JSONArray jsonObject = (JSONArray) value_expected.get("value"); 
                Iterator i = jsonObject.iterator();
                System.out.println("Values:");
                while (i.hasNext()) 
                {
                    System.out.println(""+i.next());
                }
            }
            catch (Exception ex) 
            {
                ex.printStackTrace();
            }
        }
    }

Sample file from which we are trying to capture value against key "value"

1 个答案:

答案 0 :(得分:0)

您的文件有JSONArray,而不是JSONObject。在开头检查你的Json有[]

enter image description here

JSONObject value_expected = (JSONObject) parser.parse(fileReader);

所以这一行(上)应该是这个(下面)

JSONArray value_expected = (JSONArray) parser.parse(fileReader);