javajsonsimplejson

How to convert the simple.JSONArray to normal JSONArray in Java


I am writing a JAVA program to read the JSON file data and do some processing. For reading the JSON file data from my Class path resources folder I am using the following code:

import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

String filePath = "src/main/resources/SampleRequest.json";
JSONParser parser = new JSONParser();
Object object = parser.parse(new FileReader(filePath));
JSONArray inputjsonArr = (JSONArray) object;

As we can see I am using the import org.json.simple.JSONArray to read and get the data. Instead of that, I tried using the normal JSONArray import directly import org.json.JSONArray; then I get the error:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.JSONArray

I wanted to know if it's possible to convert the simple.JSONArray to normal JSONArray. Or is it possible for me to read the data from the JSON file using the direct import org.json.JSONArray; so that I do not have to deal with this conversion at all.


Solution

  • org.json.simple and org.json are different and incompatible libraries.

    The use of org.json.simple shouldn't be recommended as it returns all of its values as an Object, whereas org.json allows to dictate what type to return.

    The solution is not to use the org.json.simple.parser.JSONParser (delete all of the org.json.simple imports) but to read the String from the relevant file and pass that to the org.json.JSONArray directly, like so:

    String json = FileUtils.readFileToString(new File( "src/main/resources/SampleRequest.json"), "UTF-8" );
    JSONArray array = new JSONArray(json);
    

    As you can see, I like to use the FileUtils from the following package for simplicity's sake, so add this dependency:

    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.8.0</version>
    </dependency>