org.json.simple.JSONArray无法转换为类org.json.simple.JSONObject

时间:2020-07-01 16:02:55

标签: java json sqlite

我一直收到此错误,已经进行了很多搜索,但似乎无法解决。基本上我正在尝试读取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();
        }
    }


2 个答案:

答案 0 :(得分:1)

将文件读入public JSONObject getCall(String url){ final JSONObject temp=null; try{ JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { JSONObject temp1; @Override public void onResponse(JSONObject response) { temp1=response; System.out.println(response); } public JSONObject getTemp1() { return temp1; } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } });} catch (Exception e){ System.out.println(e.getMessage()); } return temp; } 并解析为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

希望这会有所帮助!

答案 1 :(得分:0)

用类似这样的测试。

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