英文:
Read Json file but keys do not have quotation marks
问题
我编写了以下代码来读取文件:
JSONObject obj = (JSONObject)parser.parse(new FileReader(file.getPath()));
但是当文件内容像下面这样时,出现了错误:
{
needed:"something",
other1:true,
other2:"not important"
}
错误消息是Unexpected character (n) at position 1.
我该如何更正它?谢谢。
英文:
I wrote following code to read a file
JSONObject obj = (JSONObject)parser.parse(new FileReader(file.getPath()));
but it got error when file content is like following
{
needed:"something",
other1:true,
other2:"not important"
}
error messageUnexpected character (n) at position 1.
How could I correct it? Thanks
答案1
得分: 3
有一个简单的解决方案是使用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>
英文:
There is a simple solution Jackson library for reading unquoted fields.
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);
You can pass the file directly to readValue method.
Map items = objectMapper.readValue(new File(filePath), HashMap.class);
Instead of HashMap, you can specify your own concrete class also.
ConcreteClass items = objectMapper.readValue(new File(filePath), ConcreteClass.class);
Here is the maven dependency.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.1</version>
</dependency>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论