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();
Barbo24
  • 49
  • 6
  • Does this answer your question? [Explanation of "ClassCastException" in Java](https://stackoverflow.com/questions/907360/explanation-of-classcastexception-in-java) – xehpuk Apr 12 '20 at 00:08
  • 1
    What does the JSON look like? Can you provide a representative sample? And the `Block` class? – andrewJames Apr 12 '20 at 01: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.``` – Barbo24 Apr 12 '20 at 01:32
  • ```["{\"Inp1\":CraftBlock{pos=BlockPosition{x=6, y=56, z=0},type=REPEATER,data=Block{minecraft:repeater}[delay=1,facing=south,locked=false,powered=false],fluid=net.minecraft.server.v1_15_R1.FluidTypeEmpty@2d140a7},\"Inp2\":CraftBlock{pos=BlockPosition{x=8, y=56, z=0},type=REPEATER,data=Block{minecraft:repeater}[delay=1,facing=south,locked=false,powered=false],fluid=net.minecraft.server.v1_15_R1.FluidTypeEmpty@2d140a7},\"Gate\":CraftBlock{pos=BlockPosition{x=7, y=56, z=0},type=IRON_BLOCK,data=Block{minecraft:iron_block},fluid=net.minecraft.server.v1_15_R1.FluidTypeEmpty@2d140a7}}"]``` – Barbo24 Apr 12 '20 at 01:34
  • this is how the JSON file looks like – Barbo24 Apr 12 '20 at 01:34
  • also, since its a minecraft plugin, the Block class is from bukkit library: https://hub.spigotmc.org/javadocs/spigot/index.html?overview-summary.html – Barbo24 Apr 12 '20 at 01:35
  • 1
    This is an array with one string element. The string itself is not valid JSON. – xehpuk Apr 12 '20 at 01:49
  • How do I make it valid then? – Barbo24 Apr 12 '20 at 01:52
  • 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! – andrewJames Apr 12 '20 at 02:04
  • done, thanks for the tip – Barbo24 Apr 12 '20 at 02:12

1 Answers1

1

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, I hope this SSCCE helps:

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.

  • In the future, please consider writing a "small self-contained example" (an SSCCE like the above. It's a great way to more quickly get you a better, more accurate answer.

  • 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/

'Hope that helps - now, and in the future.

FoggyDay
  • 11,962
  • 4
  • 34
  • 48
  • 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. – Barbo24 Apr 12 '20 at 02:36
  • my question still stands – Barbo24 Feb 05 '21 at 19:49
  • 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: https://github.com/fangyidong/json-simple. It should still work, but you might prefer a "newer" alternative... – FoggyDay Feb 05 '21 at 22:42