我编写了以下代码来读取文件
JSONObject obj = (JSONObject)parser.parse(new FileReader(file.getPath()));
但是当文件内容如下时出现错误
{
needed:"something",
other1:true,
other2:"not important"
}
错误消息位置 1 处出现意外字符 (n)。
我该如何纠正它?谢谢
最佳答案
有一个简单的解决方案 jackson 库用于读取未引用的字段。
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>
关于java - 读取Json文件但key没有引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63146510/