We may sometimes need a JSON string in which the key names are not enclosed within quotation marks. In this shot, we will explore how to obtain a JSON string where the field names are not enclosed within quotes.
QUOTE_FIELD_NAMES
in JacksonWe construct an ObjectMapper
object and deactivate the JsonWriteFeature.QUOTE_FIELD_NAMES
feature to generate a JSON object whose field names are not inside quotation marks. We must use the ObjectMapper’s disable()
method to deactivate this feature.
To use the Jackson library, add the Jackson databind dependency from the Maven Repository.
import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.core.json.JsonWriteFeature;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;public class Main {public static void main(String[] args) throws JsonProcessingException {String json = "{\"name\":\"educative\",\"age\":4,\"address\":\"USA\"}";System.out.println("JSON with field names quoted - " + json);ObjectMapper objectMapper = new ObjectMapper();objectMapper.disable(JsonWriteFeature.QUOTE_FIELD_NAMES.mappedFeature());JsonNode jsonNode = objectMapper.readTree(json);String jsonStringWithoutQuotes = objectMapper.writeValueAsString(jsonNode);System.out.println("JSON with field names unquoted - " + jsonStringWithoutQuotes);}}
json
.json
to the console.ObjectMapper
class.QUOTE_FIELD_NAMES
feature using the disable()
method on the ObjectMapper
instance.json
to an instance of JsonNode
called jsonNode
.jsonNode
to a JSON string with field names unquoted called jsonStringWithoutQuotes
.jsonStringWithoutQuotes
to the console.