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

时间:2023-02-05 22:43:20

Ask: I am trying to capture the values captured inside key "value" and display it on console. However when executed getting error as"org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject"

Ask:我试图捕获键“value”内捕获的值,并将其显示在控制台。但是当执行时,会得到“org.json.simple”这样的错误。不能将JSONArray转换为org.json.simple.JSONObject"

Code Written:

编写的代码:

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 个解决方案

#1


0  

Your file has JSONArray, not JSONObject. Check your Json has [] at the begining.

您的文件有JSONArray,而不是JSONObject。检查你的Json一开始就有[]。

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

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

So this line(top) should be this (below)

这条线(上)应该是(下)

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

#1


0  

Your file has JSONArray, not JSONObject. Check your Json has [] at the begining.

您的文件有JSONArray,而不是JSONObject。检查你的Json一开始就有[]。

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

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

So this line(top) should be this (below)

这条线(上)应该是(下)

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