Read Json file but keys do not have quotation marks.

huangapple go评论71阅读模式
英文:

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 = &quot;{&quot; +
     &quot; needed:\&quot;something\&quot;,&quot; +
     &quot; other1:true,&quot; +
     &quot; other2:\&quot;not important\&quot;&quot; +
     &quot;}&quot;;
Map items = objectMapper.readValue(value,  HashMap.class);
System.out.println(&quot;Got object &quot; + 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.

&lt;dependency&gt;
    &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
    &lt;artifactId&gt;jackson-core&lt;/artifactId&gt;
    &lt;version&gt;2.11.1&lt;/version&gt;
&lt;/dependency&gt;

huangapple
  • 本文由 发表于 2020年7月29日 12:46:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63146510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定