【问题标题】:org.json.simple.JSONArray cannot be cast to class org.json.simple.JSONObjectorg.json.simple.JSONArray 不能转换为 org.json.simple.JSONObject 类
【发布时间】:2020-10-22 03:18:27
【问题描述】:

我不断收到此错误并且已经搜索了很多但似乎无法解决它。基本上我正在尝试读取一个 json 文件并将其一些数据存储在数据库中。希望大家知道如何解决这个问题! 这个 json 文件来自一个统计站点,我想将最重要的数据存储在我用 SQLite 创建的数据库表中。 谢谢大家的帮助,干杯:D

这是我不断收到的错误:

java.lang.ClassCastException: class org.json.simple.JSONArray cannot be cast to class org.json.simple.JSONObject (org.json.simple.JSONArray and org.json.simple.JSONObject are in unnamed module of loader 'app')
    at com.arrowplus.arrowplus.Connect.connect(Connect.java:49)
    at com.arrowplus.arrowplus.Connect.main(Connect.java:86)

这是我的 JSON 文件:


[ {
  "IndicadorCod" : "0010042",
  "IndicadorDsg" : "Valor mediano de avaliação bancária (€/ m²) por Localização geográfica (Município - 2013) e Tipo de construção; Mensal - INE, Inquérito à avaliação bancária na habitação",
  "MetaInfUrl" : "https://www.ine.pt/bddXplorer/htdocs/minfo.jsp?var_cd=0010042&lingua=PT",
  "DataExtracao" : "2020-06-29T15:55:51.640+01:00",
  "DataUltimoAtualizacao" : "2020-06-29",
  "UltimoPref" : "Maio de 2020",
  "Dados" : {
    "202005" : [ {
      "geocod" : "1701106",
      "geodsg" : "Lisboa",
      "dim_3" : "T",
      "dim_3_t" : "Total",
      "valor" : "3084"
    } ]
  }
} ]

这是我的代码:

package com.arrowplus.arrowplus;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.sql.Connection;
import java.sql.DriverManager;


public class Connect {


    public static Connection ConnectToDB() throws Exception {
        Connection conn = null;

            // db parameters
            String url = "jdbc:sqlite:C:/sqlite/AP.db";
            // create a connection to the database
            conn = DriverManager.getConnection(url);

            System.out.println("Connection to SQLite has been established.");
            return conn;

    }

    public static void connect() {


            //Creating a JSONParser object
            JSONParser jsonParser = new JSONParser();

            try {

                //Parsing the contents of the JSON file
                JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("C:/Users/arrowplus/Desktop/jsonTest.json"));
                //Retrieving the array
                JSONArray jsonArray = (JSONArray) jsonObject.get("");

                Connection con = ConnectToDB();
                PreparedStatement pstmt = con.prepareStatement("INSERT INTO ine_data values (id, date, valor, DataUltimoAtualizacao, geodsg)");
                for (Object object : jsonArray) {
                    JSONObject record = (JSONObject) object;
                    int id = Integer.parseInt((String) record.get("id"));
                    String date = (String) record.get("date");
                    int valor = Integer.parseInt((String) record.get("valor"));
                    String dateUpdate = (String) record.get("DataUltimoAtualizacao");
                    long dateUpdate2 = Date.valueOf(dateUpdate).getTime();
                    String city = (String) record.get("geodsg");
                    pstmt.setInt(1, id);
                    pstmt.setString(2, date);
                    pstmt.setInt(3, valor);
                    pstmt.setDate(4, new Date(dateUpdate2));
                    pstmt.setString(5, city);
                    pstmt.executeUpdate();
                }
                System.out.println("Records inserted.....");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        /**
         * @param args the command line arguments
         */
        public static void main (String[]args){
            connect();
        }
    }


【问题讨论】:

  • 您尝试将 json 从 JSONObject 转换为 JSONArray,这是不正确的。而是直接将其解析为 JSONArray,因为您的输入文件具有 json 数组而不是对象

标签: java json sqlite


【解决方案1】:

将文件读入String并解析为JSONArray

// Read file into a string
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
    stringBuilder.append(line);
    stringBuilder.append(ls);
}
// delete the last new line separator
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
reader.close();

String 转换为JSONArray

String content = stringBuilder.toString();
// convert to json array
JSONArray json = new JSONArray(content);

一一读取值:

JSONObject firstJsonObject = json.getJSONObject(1);

或遍历JSONArray

for (int i = 0; i < json.length; i++){
  JSONObject obj = json.getJSONObject(i);
  // do something
}

希望对你有帮助!!

【讨论】:

  • 谢谢你!但我似乎没有找到一种方法在此之后将值插入我的表中。你能给我一个例子,我的价值观之一将它插入到表格中吗?另外,我应该在哪里插入你给我的所有这些代码?我有点迷路了,我对此也很陌生..
  • 我的回答应该可以解决您的异常。您可以添加此代码来读取文件(您已评论的地方Parsing the contents of the JSON file)。阅读后,您可以迭代并填充您的查询。您编写准备好的陈述的方式是错误的。参考:javatpoint.com/PreparedStatement-interface
  • 尝试将字符串转换为带有“内容”字符串的 JSONArray 时出现错误:预期 0 个参数,但找到 1 个
  • 可能你的文件不是正确的json格式什么的,试试打印字符串看看值是什么
  • org.JSONArray 不适用于 foreach,请使用旧版循环 for (int i = 0; i &lt; json.length; i++)
【解决方案2】:

改用类似的东西进行测试。

Object object = (Object) jsonParser.parse(new FileReader("C:/Users/arrowplus/Desktop/jsonTest.json"));
JSONArray array = new JSONArray();
array.add(object);

【讨论】:

  • 您正在尝试将 JSONObject 转换为 JSONArray: JSONArray jsonArray = (JSONArray) jsonObject.get("");
  • 这样做之后,我是否必须更改我的 for 循环?向我的表中插入值?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多