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

2019-08-30 10:36发布

问题:

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;