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 JacksonWe 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.
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);}}
json
.json
to the console.ObjectMapper
class.ALLOW_UNQUOTED_FIELD_NAMES
feature using the enable()
method on the ObjectMapper
instance.json
to an instance of JsonNode
called jsonNode
.jsonNode
to a JSON string with field names quoted called jsonStringWithQuotes
.jsonStringWithQuotes
to the console.