Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

jackson
java
json
parse
communitycreator

How to parse single quotes JSON using Jackson in Java

abhilash

Strings in JSON

Strings in JSON are specified using double quotes, i.e., ". If the strings are enclosed using single quotes, then the JSON is an invalid JSON.

This shot talks about how to parse a JSON when the strings are enclosed with single quotes.

Using ALLOW_SINGLE_QUOTES

We can configure Jackson to allow single quotes while parsing the JSON using the ALLOW_SINGLE_QUOTES enumidentifiers that behave as constants in the language of the JsonParser class.

Note: To use the Jackson library, add the Jackson databind dependency from the Maven Repository.

Code

Let’s observe the following code example:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main{

    public static void main(String[] args) throws JsonProcessingException {
        String jsonString = "{'website':'educative','purpose': 'education','url':'https://www.educative.io'}";
        
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        
        JsonNode jsonNode = objectMapper.readValue(jsonString, JsonNode.class);
        System.out.println(jsonNode.toString());
    }
}

Explanation

  1. We create an instance of the ObjectMapper class.

  2. We configure the object mapper created in step 1 with ALLOW_SINGLE_QUOTES to true.

  3. We use the mapper instance to parse the JSON string.

To turn off the parsing of single quotes, set the configuration of ALLOW_SINGLE_QUOTES to false while configuring the object mapper instance.

RELATED TAGS

jackson
java
json
parse
communitycreator
RELATED COURSES

View all Courses

Keep Exploring