37

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(").

Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
Pipalayan Nayak
  • 937
  • 2
  • 8
  • 13

3 Answers3

79

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"}
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
16

Strings in JSON may only be specified using double quotes ("), not single quotes ('), this is the reason for your error; use double quotes.

Here's the pipe diagram that specifies valid JSON strings (note they may only be encapsulated with double quotes!)

Valid JSON Strings Pipe Diagram
(source: json.org)

(See json.org for a complete specification of JSON.)

Community
  • 1
  • 1
Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
  • 1
    Issue is i can form a absolutely valid json object with single quote in javascript, but am not able to parse that in java. Do I have to replace the single quote with double quote before parsing it with jackson – Pipalayan Nayak Jul 06 '11 at 04:04
  • 2
    @Pipalayan: the problem is that single-quotes are *not* valid in JSON, check out the specification. You cannot parse single quotes using this library because, simply put, you're giving invalid input to your parser. – Mark Elliot Jul 06 '11 at 04:06
  • 5
    "i can form a absolutely valid json object with single quote in javascript" -- JavaScript might allow the single quotes, but that doesn't mean it's valid JSON. – Programmer Bruce Jul 06 '11 at 04:22
1

This is the way it works in my case:

var jsonString ='{"it":"Stati Uniti d'America"}';
jsonString =jsonString.replace("'", "\\\\u0027");