Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

java - Configure Jackson to deserialize single quoted (invalid) JSON

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...