【问题标题】:Java - Json File Parser issueJava - Json 文件解析器问题
【发布时间】:2016-11-08 15:06:31
【问题描述】:

我正在尝试使用 Java JSONParser 读取 Json 文件中的两个对象,但在解析 Json 文件时遇到以下问题。我提供了 Java 代码和 Json 文件内容供您参考。

问题:

Unexpected token LEFT BRACE({) at position 286.
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)

Java 代码:

    public static void main(String[] args) throws Throwable {
        JSONParser  parser = new JSONParser();
         JSONObject a = null;
         Connection con = null;
         Statement stmt = null;
        try {
            Object obj = parser.parse(new FileReader("C:\\Users\\mhq175\\workspace2\\JCucumber\\JSON_FILES\\Datafile.json"));
            JSONObject jsonObject = (JSONObject) obj;
            JSONObject structure = (JSONObject) jsonObject.get("MessageContext");
            JSONObject structure_2 = (JSONObject) jsonObject.get("MessageContext1");
            con = postconn.getConnection();
            String entireFileText = "INSERT INTO Events"
                       + " VALUES ('"+ structure + "','"+ structure_2 + "');";
            System.out.println(entireFileText); 
            stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
             stmt.executeUpdate(entireFileText);
    }   catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

Json 文件:

{
    "MessageContext": {
        "field1": "VALUE1",
        "field2": "VALUE2",
        "field3": "VALUE3",
        "field4": "VALUE4",
        "field5": "VALUE5"
    },
    "MessageContext1": {
        "field1": "VALUE1",
        "field2": "VALUE2",
        "field3": "VALUE3",
        "field4": "VALUE4",
        "field5": "VALUE5"
    }
}{
    "MessageContext": {
        "field1": "VALUE1",
        "field2": "VALUE2",
        "field3": "VALUE3",
        "field4": "VALUE4",
        "field5": "VALUE5"
    },
    "MessageContext1": {
        "field1": "VALUE1",
        "field2": "VALUE2",
        "field3": "VALUE3",
        "field4": "VALUE4",
        "field5": "VALUE5"
    }
}

【问题讨论】:

  • 您是否使用任何在线工具验证了您的 JSON? }{ 不正确。我喜欢jsonlint
  • 您的 json 文件无效:它依次包含 2 个 json 对象。

标签: java json parsing


【解决方案1】:

您发送的 JSON 不正确。它由一个接一个的 2 个 JSON 对象组成,这是非法的。您必须在 JSONArray 中添加两个对象,从数组中获取单个对象并对其进行操作。 或者您可以在“}{”处拆分 Json 字符串,然后将其转换为 json 对象以进行进一步计算。

附:我知道第二种方法很脏,但这可能会让某人感到高兴。

【讨论】:

  • 如果你在}{拆分,除非你把这些字符加回来,否则它仍然是无效的
  • 这是很明白的事情。我的回答只是指路
  • 不是每个人都理解 JSON 格式(问题很明显),所以我想我会明确地说
猜你喜欢
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2012-03-23
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多