How to read a JSON string without field name quotes in Jackson
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);}}
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
jsonto the console. - Line 11: We define an instance of the
ObjectMapperclass. - Line 12: We enable the
ALLOW_UNQUOTED_FIELD_NAMESfeature using theenable()method on theObjectMapperinstance. - Line 13: We parse the
jsonto an instance ofJsonNodecalledjsonNode. - Line 14: We convert the
jsonNodeto a JSON string with field names quoted calledjsonStringWithQuotes. - Line 15: We print
jsonStringWithQuotesto the console.