0

I'm trying to read from a JSON file using json.simple java library but every time i run this code:

JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(new FileReader("plugins/LogicGates/ands.json"));
Iterator i = jsonArray.iterator();
while (i.hasNext()) {
    JSONObject obj = (JSONObject) i.next();
    Block gate = (Block) obj.get("Gate");
    Block inp1 = (Block) obj.get("Inp1");
    Block inp2 = (Block) obj.get("Inp2");
    ands.add(new And(gate, inp1, inp2));
}

it returns:

java.lang.ClassCastException: class java.lang.String cannot be cast to class org.json.simple.JSONObject (java.lang.String is in module java.base of loader 'bootstrap'; org.json.simple.JSONObject is in unnamed module of loader 'app')

Does anyone know why? Thanks in advance for any reply.

EDIT:

So I made the old code work somehow, here's how it looks now:

            JSONParser jsonParser = new JSONParser();
            JSONArray jsonArray = (JSONArray) jsonParser.parse(new FileReader("plugins/LogicGates/ands.json"));
            Iterator i = jsonArray.iterator();
            while (i.hasNext()) {
                JSONParser parser = new JSONParser();
                JSONObject obj = (JSONObject) parser.parse((String) i.next());
                Block gate = (Block) obj.get("Gate");
                Block inp1 = (Block) obj.get("Inp1");
                Block inp2 = (Block) obj.get("Inp2");
                ands.add(new And(gate, inp1, inp2));
            }

But now I'm getting a completely different error:

Unexpected character (C) at position 8.

I was told that my JSON is not valid so here's the code that writes the JSON:

            FileWriter writer = new FileWriter("plugins/LogicGates/ands.json");
            JSONArray jsonArray = new JSONArray();
            JSONObject obj = new JSONObject();
            for(And a : ands) {
                obj.put("Gate", a.getGate());
                obj.put("Inp1", a.getInp1());
                obj.put("Inp2", a.getInp2());
                jsonArray.add(obj.toJSONString());
            }
            writer.write(jsonArray.toJSONString());
            writer.close();
10
  • Does this answer your question? Explanation of "ClassCastException" in Java Commented Apr 12, 2020 at 0:08
  • 1
    What does the JSON look like? Can you provide a representative sample? And the Block class? Commented Apr 12, 2020 at 1:25
  • Ok, so i fixed the reading error with some parsing, but now i have a completely different error: Unexpected character (C) at position 8. Commented Apr 12, 2020 at 1:32
  • 1
    This is an array with one string element. The string itself is not valid JSON. Commented Apr 12, 2020 at 1:49
  • 1
    Can you edit your question to include this new information, instead of using comments? Small point, but it is generally easier to read, that way. And thank you for the updates! Commented Apr 12, 2020 at 2:04

1 Answer 1

0

I wrote this example before you updated your post.

I assumed you were probably using GSON ... but you haven't told us exactly which library you're using, nor given an example of your file format.

Anyway, try this:

test.json

{
  "books": [
    {"title":"The Shining", "author":"Stephen King"},
    {"title":"Ringworld","author":"Larry Niven"},
    {"title":"The Moon is a Harsh Mistress","author":"Robert Heinlein"}
  ]
}

HelloGson.java

package com.example.hellogson;

import java.io.FileReader;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * Illustrates one way to use GSON library to parse a JSON file
 * 
 * EXAMPLE OUTPUT:
 *   Author: Stephen King, title: The Shining
 *   Author: Larry Niven, title: Ringworld
 *   Author: Robert Heinlein, title: The Moon is a Harsh Mistress
 *   Done parsing test.json
 */
public class HelloGson {
    
    public static final String FILENAME = "test.json";
    
    public static void main(String[] args ) {
        try {
            // Open file 
            FileReader reader = new FileReader(FILENAME);

            // Parse as JSON.  
            // Typically, the toplevel element will be an "object" (e.g."books[]" array
            JsonParser jsonParser = new JsonParser();
            JsonElement rootElement = jsonParser.parse(reader);
            if (!rootElement.isJsonObject()) {
                throw new Exception("Root element is not a JSON object!");
            }
            
            // OK: Get "books".  Let's assume it's an array - we'll get an exception if it isn't.
            JsonArray books = ((JsonObject)rootElement).get("books").getAsJsonArray();
            for (JsonElement book : books) {
                // Let's also assume each element has an "author" and a "title"
                JsonObject objBook = (JsonObject)book;
                String title = objBook.get("title").getAsString();
                String author = objBook.get("author").getAsString();
                System.out.println("Author: " + author + ", title: " + title);
            }

            System.out.println("Done parsing " + FILENAME);
        } catch (Exception e) {
            System.out.println("EXCEPTION: " + e.getMessage());
            e.printStackTrace();
        }
    }

}

Notes:

  • Perhaps a better approach, rather than mapping individual JSON elements, is to map your entire JSON data structure to Java objects. GSON supports this; Jackson is another commonly used Java library.

  • Finally, no library is going to help you if your JSON isn't well-formed. There are many on-line validation checkers. For example: https://jsonlint.com/

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

3 Comments

What do you mean by I assumed you were probably using GSON ... but you haven't told us exactly which library you're using the library is right in the title of this post.
my question still stands
Ten months later (Feb 2021) and you still can't do some simple JSON in Java? What's up with that? SUGGESTION: 1) Update your post with short code illustrating your CURRENT problem. 2) Copy/paste the EXACT ERROR TEXT of the current problem. PS: It looks like json.simple hasn't been updated in about 9 years: github.com/fangyidong/json-simple. It should still work, but you might prefer a "newer" alternative...

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.