Json.net how to use jsonpath with “$.”

£可爱£侵袭症+ 提交于 2019-12-11 17:57:24

问题


I'm trying to use json.net from json as follows:

String JSONString =
@"[
    {
      ""category"": ""reference"",
      ""author"": ""Nigel Rees"",
      ""title"": ""Sayings of the Century"",
      ""price"": 8.95
    },
    {
      ""category"": ""fiction"",
      ""author"": ""Still Here"",
      ""title"": ""Test remove title"",
      ""price"": 12.99,
      ""isbn"": ""0-553-21311-3""
    }
  ]";

JObject JSONObject;
JSONObject = JObject.Parse(JSONString);

String JSONPath = @"$[0].title";
JSONObject.SelectToken(JSONPath);

Getting Exception:

ST.Acxiom.Test.DataJSONTest.DataJSONClass.GetToken: Newtonsoft.Json.JsonException :   Property '$' does not exist on JObject.   
  • What I'm doing wrong, even though I'm using valid jsonpath but still getting error.
  • Is "$." not supported?
  • How to access Array item in json in above example?

Any help would be appreciated.


回答1:


  1. Using JObject.Parse from your example throws JsonReaderException with the latest Json.net version. You have to use either JToken.Parse or JsonConvert.DeserializeObject.
  2. SelectToken is intended to select child nodes so $ is not supported. You can access array item like this:
var jArray = JToken.Parse(JSONString); //It's actually a JArray, not a JObject
var jTitle = jArray.SelectToken("[0].title");
var title = (string)jTitle;


来源:https://stackoverflow.com/questions/14348567/json-net-how-to-use-jsonpath-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!