Parsing a json to a java object

by Oliver   Last Updated March 13, 2018 00:05 AM

I have this json file

{ "id":1, "name":"Han Solo", "shipsType":["A","B","C"] },

{ "id":2, "name":"Yoda", "shipsType":[] },

{ "id":3, "name":"Luke Skywalker", "shipsType":["B","C"] }

And I want to parse it into a java object with this code :

public class Main {
public static void main(String[] args) {
    JSONParser parser = new JSONParser();
    try {

        Object obj = parser.parse(new FileReader("/Users/Alex/Desktop/problema/characters.json"));

        JSONObject jsonObject = (JSONObject) obj;

        // JSONArray array = new JSONArray();
        // array.add(obj);

        String id = (String) jsonObject.get("id");
        String name = (String) jsonObject.get("name");
        JSONArray shipsType = (JSONArray) jsonObject.get("Ships list");

        System.out.println("Id " + id);
        System.out.println("Name: " + name);
        System.out.println("\nShips List:");
        Iterator<String> iterator = shipsType.iterator();
        while (iterator.hasNext()) {

    } catch (Exception e) {


But i get this error : " java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject at problema.Main.main("

Why ? Please help me

Tags : java json

Answers 1

I believe the answer is apparent from the error message: you are trying to cast a JsonArray into a JsonObject.

So the question is then, why is your obj variable a JsonArray object and not a JsonObject object as you expect it to be? Well, it looks to me like your file has multiple objects in it. The json parser might be treating it as an array (as if the entire contents you pasted were enclosed in [] brackets). You might want to try setting up your file to just look like this:

{ "id":1, "name":"Han Solo", "shipsType":["A","B","C"] }

and nothing else, and seeing what happens.

EDIT: alternatively, and perhaps more in line with what you want to accomplish here, you may want to cast your obj variable to a JSONArray and then iterate over it

K. M
K. M
March 12, 2018 23:37 PM

Related Questions

Data Driven Validation/Rule Engine in JAVA

Updated July 23, 2015 13:02 PM

Java - Parsing mixed XML/HTML String to JSON

Updated June 10, 2015 03:02 AM