开发者

Configure Jackson to deserialize single quoted (invalid) JSON

开发者 https://www.devze.com 2023-03-18 11:02 出处:网络
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

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


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


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!)

Configure Jackson to deserialize single quoted (invalid) JSON


(source: json.org)

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


This is the way it works in my case:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号