且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

配置 Jackson 反序列化单引号(无效)JSON

更新时间:2022-10-24 10:38:23

这不是有效的 JSON,但您可以告诉 Jackson 允许它.方法如下.

String x = "{'candidateId':'k','candEducationId':1,'activitiesSocieties':'Activity 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());//输出:{"candidateId":"k","candEducationId":1,"activitiesSocieties":"Activity for cand1"}

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