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.
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
Jackson
library, add theJackson
databind
dependency from the Maven Repository.
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());}}
We create an instance of the ObjectMapper
class.
We configure the object mapper created in step 1 with ALLOW_SINGLE_QUOTES
to true.
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
tofalse
while configuring the object mapper instance.