【问题标题】:Read Json file but keys do not have quotation marks读取 Json 文件但键没有引号
【发布时间】:2020-07-29 04:46:34
【问题描述】:

我写了以下代码来读取文件

JSONObject obj = (JSONObject)parser.parse(new FileReader(file.getPath()));

但是当文件内容如下时出现错误

{
 needed:"something",
 other1:true,
 other2:"not important"
}

错误信息Unexpected character (n) at position 1.

我该如何纠正它?谢谢

【问题讨论】:

  • 您拥有的文件不是 JSON。您也许能够做一些事情,比如将其视为 JavaScript 并通过 JS 引擎运行它,但修复损坏的输入是正确的方法。
  • 最简单的方法是从外部纠正 JSON 格式并使用当前方法读取文件。

标签: java json parsing


【解决方案1】:

有一个简单的解决方案 Jackson library 用于读取未引用的字段。

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
String value = "{" +
     " needed:\"something\"," +
     " other1:true," +
     " other2:\"not important\"" +
     "}";
Map items = objectMapper.readValue(value,  HashMap.class);
System.out.println("Got object " + items);

您可以将文件直接传递给 readValue 方法。

Map items = objectMapper.readValue(new File(filePath),  HashMap.class);

您也可以指定自己的具体类来代替 HashMap。

ConcreteClass items = objectMapper.readValue(new File(filePath),  ConcreteClass.class);

这里是maven依赖。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.11.1</version>
</dependency>

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2017-06-24
    • 2021-05-12
    • 2021-06-01
    • 1970-01-01
    • 2020-09-07
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多