如何处理过滤器表达式中的撇号?

How handle apostrophe in filter expression?

给定一些 json:

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : "Bill's Automotive",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
}

我想return Bill's Automotive phone 号码对象:

{
  "type"  : "Bill's Automotive",
  "number": "0123-4567-8888"
}

使用 Json.NET,它使用 jsonpath 语法,我有过滤器表达式:

phoneNumbers.[?(@.type=="Bill's Automotive")]

当您在以下平台上测试它时,它工作正常:

您可以在哪里亲自尝试。

但在 Json.net

中失败

但在 C# 中,在运行时,使用 Newtonsoft Json.Net,代码抛出异常:

JToken billsPhone= o.SelectToken("phoneNumbers.[?(@.type=="Bill's Automotive")]");

Newtonsoft.Json.JsonException: Unexpected character while parsing path query: s

显然它看到了撇号,并认为它是查询字符串的结尾。

我尝试过的其他变化

所以我放弃了

如何在 Newtonsoft Json.NET 中过滤 json?

您需要为查询提供反斜杠转义引号:

JToken billsPhone = o.SelectToken("phoneNumbers.[?(@.type=='Bill\'s Automotive')]");

请注意,您需要用单引号将搜索词和 \ 括起来,因此最终字符串实际上包含 \'.

我不知道如何使用 SelectToken,但是 请参阅 Alexei 的转义引号答案,但您可以使用一些 [=12] =].

 var billsPhone = o["phoneNumbers"]
                  .FirstOrDefault(t => t["type"].Value<string>() == "Bill's Automotive");

Use a verbatim string

JToken billsPhone = o.SelectToken(@"phoneNumbers.[?(@.type==""Bill's Automotive"")]");

What is the difference between a regular string and a verbatim string?

Can I escape a double quote in a verbatim string literal?