Read Json file but keys do not have quotation marks

Viewed 96

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 Answers

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>
Related