1

I keep getting this error and already searched a lot and cant seem to solve it. Basically i am trying to read a json file and store some of its data in a database. Hope you guys know how to solve this! This json file is from a statistics site and i want to store the most important data in a database table i created with SQLite. Thanks for all the help, cheers :D

This is the error i keep getting:

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)

This is my JSON file:


[ {
  "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"
    } ]
  }
} ]

And this is my code:

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();
        }
    }


1
  • You trying to cast a json from JSONObject to JSONArray which is incorrect. Instead parse it to a JSONArray directly as your input file has a json array and not object Commented Jul 9, 2020 at 9:00

2 Answers 2

2

Read file into String and parse as 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();

Convert the String to a JSONArray:

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

Read values one by one:

JSONObject firstJsonObject = json.getJSONObject(1);

or iterate through the JSONArray

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

Hope this helps !!

Sign up to request clarification or add additional context in comments.

11 Comments

thanks man! but i dont seem to find a way to insert values into my table after this. can you give me an example with one of my values inserting it into the table? also, where should i insert all this code you gave me? im kind of lost here, im also new to this..
My answer should fix your exception. You can add this code to read the file (the place you have commented Parsing the contents of the JSON file). Once read, you can iterate and populate your query. The way you have written your prepared statement is wrong. Refer: javatpoint.com/PreparedStatement-interface
i get an error when trying to convert String to a JSONArray with the "content" string: Expected 0 arguments but found 1
probably your file is not in proper json format or something, try printing the string and see whats the value
org.JSONArray doesnt work with foreach, use legacy loops for (int i = 0; i < json.length; i++)
|
-1

Test with something like this instead.

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

2 Comments

There you are trying to cast JSONObject to JSONArray: JSONArray jsonArray = (JSONArray) jsonObject.get("");
doing that, will i have to change my for loop after that? to insert values into my table?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.