How to get a JSON string without field name quotes in Jackson
Overview
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 Jackson
We 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.
Code example
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);}}
Code explanation
- Lines 1-4: We import the relevant packages and classes.
- Line 9: We define a JSON string with quotes called
json. - Line 10: We print
jsonto the console. - Line 11: We define an instance of the
ObjectMapperclass. - Line 12: We disable the
QUOTE_FIELD_NAMESfeature using thedisable()method on theObjectMapperinstance. - Line 13: We parse the
jsonto an instance ofJsonNodecalledjsonNode. - Line 14: We convert the
jsonNodeto a JSON string with field names unquoted calledjsonStringWithoutQuotes. - Line 15: We print
jsonStringWithoutQuotesto the console.