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 😀
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(); } }
Advertisement
Answer
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 !!