Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
jackson
json
communitycreator

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

abhilash

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 json to the console.
  • Line 11: We define an instance of the ObjectMapper class.
  • Line 12: We disable the QUOTE_FIELD_NAMES feature using the disable() 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 unquoted called jsonStringWithoutQuotes.
  • Line 15: We print jsonStringWithoutQuotes to the console.

RELATED TAGS

java
jackson
json
communitycreator
RELATED COURSES

View all Courses

Keep Exploring