java - json.simple 无法将 String 转换为 JSONObject 错误

标签 java json

我正在尝试使用 json.simple java 库读取 JSON 文件,但每次运行此代码时:

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

它返回:

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')

有人知道为什么吗?预先感谢您的回复。

编辑:

所以我让旧代码以某种方式工作,现在看起来是这样的:

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

但现在我遇到了完全不同的错误:

Unexpected character (C) at position 8.

我被告知我的 JSON 无效,因此这是编写 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();

最佳答案

我在您更新帖子之前编写了这个示例。

我假设您可能正在使用 GSON ...但您没有确切地告诉我们您正在使用哪个库,也没有给出文件格式的示例。

无论如何,我希望这个SSCCE帮助:

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

}

注释:

  • 也许更好的方法是将整个 JSON 数据结构映射到 Java 对象,而不是映射单个 JSON 元素。 GSON支持这一点; Jackson是另一个常用的 Java 库。

  • 将来,请考虑编写一个“小型独立示例”(如上面的 SSCCE。这是更快地为您提供更好、更准确答案的好方法。

  • 最后,如果您的 JSON 格式不正确,NO 库不会为您提供帮助。有许多在线验证检查器。例如:https://jsonlint.com/

“希望这对现在和将来有所帮助。

关于java - json.simple 无法将 String 转换为 JSONObject 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61165203/

相关文章:

java应用程序更新程序

java - Java 从 ArrayList 中删除

javascript - JSON 编码为 Javascript

c# - 将对象转换为 JSON,然后将该 JSON 下载为文本文件 [Asp.net core]

java - 从 Firebase 存储检索图像下载 url

java - 图形使用值 0.01f 和 2f : what is this format?

java - java编译器如何在类路径未设置为jdk路径的情况下找到类文件?

java - 比较 Java 中的两个 JsonArray 节点

c# - 无效的匿名类型成员声明符 c# linq?

html - 在 angularjs 中使用 ng-repeat 动态创建表