JSON.net SelectToken()在路径中带有单引号

时间:2016-06-18 03:03:49

标签: json json.net

考虑一下这个json:

{
    "farms": [
        {
            "fred's": {
                "cows": 5,
                "pigs": 2,
                "horses": "none"
            }
        }, {
            "old mcdonald's": {
                "cows": none,
                "pigs": 1,
                "horses": 3
            }
        }
    ]
}

单独使用单引号似乎没有问题:

JObject j = new JObject();
JToken jt = j.SelectToken(farms.fred's);

但是,尝试同时使用单引号和空格时会发生错误。

使用此代码:

JObject j = new JObject();
JToken jt = j.SelectToken(farms.old mcdonald's);

我收到了这个错误:

  

JsonException:解析路径时出现意外的字符

所以我做了一些搜索,发现带有空格的术语必须包围:

[' ']

示例:

JObject j = new JObject();
JToken jt = j.SelectToken(farms.['old mcdonald's']);

但是,现在错误是:

  

JsonException:解析路径索引器时出现意外的字符:s

是否可以在SelectToken路径中包含空格和单引号?

1 个答案:

答案 0 :(得分:2)

似乎是......

var x = @"{
    ""farms"": [
        {
            ""fred's"": {
                ""cows"": 5,
                ""pigs"": 2,
                ""horses"": ""none""
            }
        },
        {
            ""old mcdonald's"": {
                ""cows"": ""none"",
                ""pigs"": 1,
                ""horses"": 3
            }
        }
    ]
}";

var j = JObject.Parse(x);
var jobj = j.SelectToken("farms[1]['old mcdonald\\'s']") as JObject;
jobj.Properties().Select( p => p.Name + ": " + p.Value).Dump();
IEnumerable<String> (3 items)
* cows: none 
* pigs: 1 
* horses: 3