Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Jackson to deserialize single quoted (invalid) JSON

Tags:

java

jackson

I am a newbie to using jackson library.

I am trying to do this [see below], and it is throwing error.

String x="{'candidateId':'k','candEducationId':1,'activitiesSocieties':'Activities for cand1'}"; ObjectMapper mapper = new ObjectMapper();  try {     JsonNode df=mapper.readValue(x,JsonNode.class);     int i=0; } catch ..... 

Exception:

org.codehaus.jackson.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name at [Source: java.io.StringReader@1afd1810; line: 1, column: 3]   at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1291) 

While the same thing works if I replace the single quote(') with double quote(").

like image 874
Pipalayan Nayak Avatar asked Jul 06 '11 03:07

Pipalayan Nayak


People also ask

How do I convert JSON objects to Jackson?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

What is JsonIgnoreProperties ignoreUnknown true?

We have just annotated a whole model class as @JsonIgnoreProperties(ignoreUnknown = true), which mean any unknown property in JSON String i.e. any property for which we don't have a corresponding field in the EBook class will be ignored. If you compile and run your program again it will work fine.

Is Jackson ObjectMapper case sensitive?

Jackson is a well-known library for JSON utilities. It has a wide area of features. One of them is case insensitive deserialization for field names.

How does Jackson JSON work?

The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON. The Jackson ObjectMapper can also create JSON from Java objects.


1 Answers

It's not valid JSON, but you can tell Jackson to allow it. Here's how.

String x = "{'candidateId':'k','candEducationId':1,'activitiesSocieties':'Activities for cand1'}"; ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); JsonNode df = mapper.readValue(x, JsonNode.class); System.out.println(df.toString()); // output: {"candidateId":"k","candEducationId":1,"activitiesSocieties":"Activities for cand1"} 
like image 53
Programmer Bruce Avatar answered Oct 04 '22 15:10

Programmer Bruce