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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6591388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:01:45  来源:igfitidea点击:

Configure Hymanson to deserialize single quoted (invalid) JSON

javaHymanson

提问by Pipalayan Nayak

I am a newbie to using Hymanson library.

我是使用 Hymanson 库的新手。

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.Hymanson.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.Hymanson.JsonParser._constructError(JsonParser.java:1291)
org.codehaus.Hymanson.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.Hymanson.JsonParser._constructError(JsonParser.java:1291)

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

如果我用双引号(“)替换单引号('),同样的事情也会起作用。

采纳答案by Programmer Bruce

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

它不是有效的 JSON,但您可以告诉 Hymanson 允许它。就是这样。

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

回答by Mark Elliot

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

JSON 中的字符串只能使用双引号 ( ")指定,而不是单引号 ( '),这是您出错的原因;使用双引号。

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

这是指定有效 JSON 字符串的管道图(注意它们只能用双引号封装!)

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

有效的 JSON 字符串管道图
(来源:json.org

(See json.orgfor a complete specification of JSON.)

(有关JSON 的完整规范,请参阅json.org。)

回答by user2918934

This is the way it works in my case:

这是它在我的情况下的工作方式:

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