1

I'm trying to parse a file in order to POST JSON data into a local platform which requires an access token. but I'm getting this error: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject.

I've tried many ways to fix it, but I didn't work.

Here's the code : here's a part which i used it to convert my csv file into Json format

import java.io.File;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.DataInputStream;
import java.io.File;
//import org.json.JSONObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.JSONArray;

public class CSVtoJSON {
     public static void main(String[] args) throws Exception {
            File input = new File("ArgosData_2020_05_24_22_21_59.csv");
            File output = new File("output.json");
            String access_token = "rxmqDZF0J1BCUIDm1Faw";

            CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();
            CsvMapper csvMapper = new CsvMapper();

            // Read data from CSV file
            List<Object> readAll = csvMapper.readerFor(Map.class).with(csvSchema).readValues(input).readAll();

            ObjectMapper mapper = new ObjectMapper();

            // Write JSON formated data to output.json file
            mapper.writerWithDefaultPrettyPrinter().writeValue(output, readAll);

            // Write JSON formated data to stdout
            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(readAll));

And then I tried to post the data, in this part i got the error message :

 try {
                JSONParser parser = new JSONParser();
                //Use JSONObject for simple JSON and JSONArray for array of JSON.
                JSONObject data = (JSONObject) parser.parse(
                        new FileReader(output.getAbsolutePath()));//path to the JSON file.
                System.out.println(data.toJSONString());

                String paramValue = "param\\with\\backslash";
                String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");

                URL url2 = new URL("http://localhost:8080");
                HttpsURLConnection conn = (HttpsURLConnection) url2.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Accept", "application/json");
                conn.setRequestProperty("Authorization", "Bearer" + access_token);

                conn.setDoOutput(true);
                OutputStream outStream = conn.getOutputStream();
                OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
                outStreamWriter.write(data.toJSONString());
                outStreamWriter.flush();
                outStreamWriter.close();
                outStream.close();
                String response = null;

                System.out.println(conn.getResponseCode());
                System.out.println(conn.getResponseMessage());

                DataInputStream input1 = null;
                input1 = new DataInputStream (conn.getInputStream());
                while (null != ((response = input1.readLine()))) {
                    System.out.println(response);
                    input1.close ();
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
        }

}



If anybody who has a clue how to do so, I'm new to programming and I'd be grateful to get some help.

1
  • Let me get this clear, you’re writing a list to a json, not a JsonObject, and are now trying to cast that list (JsonArray) to a JsonObject? Commented Jun 4, 2020 at 19:15

1 Answer 1

1

You are writing a list of objects and try to read a single object.

If you look at the file, you probably see something like this:
[{"name": "Object1", value="1"}, {"name": "Object2"}, {"name": Object3"}].

With JSONObject data = (JSONObject) parser.parse(... you're trying to read a single JSON object, e.g. {"name":"i'm a single object' "value"="42"}. To fix the imminent problem, use JSONArray data instead of JSONObject like the message suggests.

I'm not familiar with org.json.simple and couldn't see to find this specific library, so I currently cannot suggest any further code snippets to try.

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

1 Comment

I agree with you, actually I have a list of objects so I think maybe that's the problem, I'll try to use JSONArray instead and see if it can solve it.

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.