简体   繁体   中英

json.simple cant cast String to JSONObject error

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM