How to parse single quotes JSON using Jackson in Java
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 JsonParser class.
Note: To use the
Jacksonlibrary, add theJacksondatabinddependency 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
-
We create an instance of the
ObjectMapperclass. -
We configure the object mapper created in step 1 with
ALLOW_SINGLE_QUOTEStotrue. -
We use the
mapperinstance to parse theJSONstring.
To turn off the parsing of single quotes, set the configuration of
ALLOW_SINGLE_QUOTEStofalsewhile configuring the object mapper instance.