Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

jackson
communitycreator
java
json

How to read a JSON string without field name quotes in Jackson

abhilash

Overview

We often have to read JSON values where the field names are not quoted, i.e., when enclosed with double ("") or single ('') quotes. This shot explores how to read a JSON string where the field names are not enclosed within quotes.

ALLOW_UNQUOTED_FIELD_NAMES in Jackson

We construct an ObjectMapper object and activate the JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES feature. This generates a JSON Object where field names are quoted. To activate this feature, we must use the ObjectMapper’s enable() method and provide the feature to be enabled.

To use the Jackson library, add the Jackson data-bind dependency from the Maven Repository.

Code

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main1 {

    public static void main(String[] args) throws JsonProcessingException {
        String json = "{name:\"educative\",age:4,address:\"USA\"}";
        System.out.println("JSON without field names quoted - " + json);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES.mappedFeature());
        JsonNode jsonNode = objectMapper.readTree(json);
        String jsonStringWithQuotes = objectMapper.writeValueAsString(jsonNode);
        System.out.println("JSON with field names quoted - " + jsonStringWithQuotes);
    }
}
Reading a string without field name quotes

Explanation

  • Line 1 to 4: We import the relevant packages and classes.
  • Line 9: We define a JSON string with unquoted field names called json.
  • Line 10: We print the json to the console.
  • Line 11: We define an instance of the ObjectMapper class.
  • Line 12: We enable the ALLOW_UNQUOTED_FIELD_NAMES feature using the enable() method on the ObjectMapper instance.
  • Line 13: We parse the json to an instance of JsonNode called jsonNode.
  • Line 14: We convert the jsonNode to a JSON string with field names quoted called jsonStringWithQuotes.
  • Line 15: We print jsonStringWithQuotes to the console.

RELATED TAGS

jackson
communitycreator
java
json
RELATED COURSES

View all Courses

Keep Exploring