How to read json file into java with simple JSON library

convert json file to string java
read json file in java using jackson
json-simple jar
gson read json file
java read json file from resources
java json parser example
java json library
write multiple json objects to file java

I want to read this JSON file with java using json simple library.

My JSON file looks like this:

[  
    {  
        "name":"John",
        "city":"Berlin",
        "cars":[  
            "audi",
            "bmw"
        ],
        "job":"Teacher"
    },
    {  
        "name":"Mark",
        "city":"Oslo",
        "cars":[  
            "VW",
            "Toyata"
        ],
        "job":"Doctor"
    }
]

This is the java code I wrote to read this file:

package javaapplication1;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JavaApplication1 {
    public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        try {     
            Object obj = parser.parse(new FileReader("c:\\file.json"));

            JSONObject jsonObject =  (JSONObject) obj;

            String name = (String) jsonObject.get("name");
            System.out.println(name);

            String city = (String) jsonObject.get("city");
            System.out.println(city);

            String job = (String) jsonObject.get("job");
            System.out.println(job);

            // loop array
            JSONArray cars = (JSONArray) jsonObject.get("cars");
            Iterator<String> iterator = cars.iterator();
            while (iterator.hasNext()) {
             System.out.println(iterator.next());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

But I get the following exception:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject at javaapplication1.JavaApplication1.main(JavaApplication1.java:24)

Can somebody tell me what I am doing wrong? The whole file is a array and there are objects and another array (cars) in the whole array of the file. But i dont know how I can parse the whole array into a java array. I hope somebody can help me with a code line which I am missing in my code.

Thanks

The whole file is an array and there are objects and other arrays (e.g. cars) in the whole array of the file.

As you say, the outermost layer of your JSON blob is an array. Therefore, your parser will return a JSONArray. You can then get JSONObjects from the array ...

  JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));

  for (Object o : a)
  {
    JSONObject person = (JSONObject) o;

    String name = (String) person.get("name");
    System.out.println(name);

    String city = (String) person.get("city");
    System.out.println(city);

    String job = (String) person.get("job");
    System.out.println(job);

    JSONArray cars = (JSONArray) person.get("cars");

    for (Object c : cars)
    {
      System.out.println(c+"");
    }
  }

For reference, see "Example 1" on the json-simple decoding example page.

Java read json and write json example, It's a simple JSON object with 3 arrays which you could parse it very easily? Do you have a code which is not working? Please share and i'll be able to check  3. Read JSON from file in Java with json-simple. To read JSON from file, we will be using the JSON file we created in the previous example. First of all, we will create JSONParser instance to parse JSON file. Use FileReader to read JSON file and pass it to parser. Start reading the JSON objects one by one, based on their type i.e. JSONArray and JSONObject.

You can use jackson library and simply use these 3 lines to convert your json file to Java Object.

ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);

How to Read JSON Object From File in Java? • Crunchify, JSON.simple is a simple Java library for JSON processing, read and try (​FileWriter file = new FileWriter("c:\\projects\\test.json")) { file.write(obj. In an earlier article, I wrote about reading and writing JSON files in Java using different open-source libraries. In this article, I will focus on one of those libraries — JSON.simple — to convert Java Objects into JSON and back. JSON.simple is a lightweight Java library for processing JSON that can be used to read, write, and parse JSON.

Add Jackson databind:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0.pr2</version>
</dependency>

Create DTO class with related fields and read JSON file:

ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);

JSON.simple – Read and write JSON, As there is no native support for JSON in Java, first of all, we should add a To begin with, we'll use the json-simple module, adding it as a Maven dependency read the JSON object from the file and print it to the console either completely A library that will allow us to do all this in a very efficient manner is called Jackson  First we start by getting the InputStream of the JSON file to be read using getResourceAsStream () method. Next we construct a JSONTokener from the input stream and create an instance of JSONObject to read the JSON entries. We can use method like getString (), getInt (), getLong (), etc to read a key-value from the JSON file.

Reading from JsonFile

public static ArrayList<Employee> readFromJsonFile(String fileName){
        ArrayList<Employee> result = new ArrayList<Employee>();

        try{
            String text = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);

            JSONObject obj = new JSONObject(text);
            JSONArray arr = obj.getJSONArray("employees");

            for(int i = 0; i < arr.length(); i++){
                String name = arr.getJSONObject(i).getString("name");
                short salary = Short.parseShort(arr.getJSONObject(i).getString("salary"));
                String position = arr.getJSONObject(i).getString("position");
                byte years_in_company = Byte.parseByte(arr.getJSONObject(i).getString("years_in_company")); 
                if (position.compareToIgnoreCase("manager") == 0){
                    result.add(new Manager(name, salary, position, years_in_company));
                }
                else{
                    result.add(new OrdinaryEmployee(name, salary, position, years_in_company));
                }
            }           
        }
        catch(Exception ex){
            System.out.println(ex.toString());
        }
        return result;
    }

Reading and Writing JSON in Java, JSON Processing in Java : The Java API for JSON Processing JSON.simple is a simple Java library that allow parse, generate, transform, and query JSON. JSON data into a file “JSONExample.json”, with help of JSONObject and JSONArray. In an earlier article, I wrote about reading and writing JSON in Java by using multiple JSON processing libraries like JSON.simple, Jackson, Moshi, and Gson. In this article, you'll learn how to read and write JSON using Jackson. Jackson is a popular open-source library for processing JSON in

You can use Gson for this. GSON is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

Take a look of this Converting JSON to Java

How to parse JSON in Java, Here we show how to parse JSON in Java using the org.json library. A JSON To use org.json to parse JSON in Java, you need to add the library as a dependency. The above two examples require a full deserialization of the JSON into a Java object before How to Delete Files and Directories in Java. For this tutorial we have downloaded and installed JSON.simple and have added the location of json-simple-1.1.1.jar file to the environment variable CLASSPATH. Mapping between JSON and Java entities. JSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while encoding.

How to Parse JSON in Java, The json.simple is a lightweight JSON processing library that can be used to read and write JSON files and it can be used to encode or decode  How to parse JSON in Java JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays.

How can we read a JSON file in Java?, Learn how to read and write JSON files using JSON.simple, Jackson, Gson, and Mushi open-source libraries. We can do this by using JSON simple library. Just download the library from below and add this library to your eclipse java project where you will make class to read and write JSON file. Step 1: To write JSON File. Here, first we will create a JSON file and write some data in it. To do this make a class named "JSONWrite" in java eclipse.

Reading and Writing JSON Files in Java, In an earlier article, I wrote about reading and writing JSON files in Java using different open-source libraries. In this article, I will focus on one  How to Parse JSON Data From a REST API Using a Simple JSON Library This quick tutorial will show you how you can use JAVA to leverage JSON data from a REST API and parse it as a JSON object. by

Comments
  • Thanks. It reads the first object course, instructor, students array and title object. How can I read the next ones too?
  • Well, you want to process all of the items in the array in a loop. My code just gets you the first item (a.get(0)) because that was the closest match to your original code. The json-simple documentation says a JSONArray is java.util.List, so you can iterate over the elements just like you would a normal list. Is that enough to go on?
  • I have tried that but it did not work. Can you give me a code example
  • This works great ! Please note: use the import as is in this example (i.e. with 'simple'), otherwise it will not allow 'for each'. Wrong: import org.json.JSONArray; import org.json.JSONObject; Correct: import org.json.simple.JSONArray; import org.json.simple.JSONObject;
  • parser from which library (import) is it?
  • May i know the ObjectMapper jar links to download.
  • @RenceAbishek you import it with import com.fasterxml.jackson.databind.ObjectMapper;
  • You think he should switch libraries because he hit one snag? Not exactly the most direct route to getting his program working ... ;-)
  • Unexpected token LEFT BRACE({) at position 156.
  • You JSON file has a array of object so travers through the array
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
  • The Original question asks about reading into an JSON Object not a string.