How to use Jsonpath in System.text.json

  • Thread starter Thread starter zydjohn
  • Start date Start date
Z

zydjohn

Guest
Hello:

I have some sample json data, like this:

[{ "CloseDate": "2019-10-20T10:00:00Z",

"Status": 1,

"ID": 1234567890

},

{ "CloseDate": "2019-10-20T10:00:00Z",

"Status": 0,

"ID": 1234567891

},

{ "CloseDate": "2019-10-15T10:00:00Z",

"Status": 1,

"ID": 1234567892

}]


I want to write a function to find those json records’ "ID" whose "Status" is 1.

And better to save them in a directory using ID as key and "CloseDate" as value, like this:

varDclose_Date = newDictionary<long, DateTime>()

{ { 1234567890, DateTime.Parse("2019-10-20T10:00:00Z") },

{ 1234567892, DateTime.Parse("2019-10-15T10:00:00Z") }, };

With Newtonsoft.json, I can easily get the first job done.



public class RootObject
{
public DateTime CloseDate { get; set; }
public int Status { get; set; }
public long ID { get; set; }
}

string root_json_data =
@"[{ ""CloseDate"": ""2019-10-20T10:00:00Z"", ""Status"": 1, ""ID"": 1234567890},
{ ""CloseDate"": ""2019-10-10T10:00:00Z"", ""Status"": 0, ""ID"": 1234567891},
{ ""CloseDate"": ""2019-10-15T10:00:00Z"", ""Status"": 1, ""ID"": 1234567892}]";
string jsonpath1 = "$..[?(@.Status == 1)].ID";
JArray json_array1 = JArray.Parse(root_json_data);
var status_array1= json_array1.SelectTokens(jsonpath1);


But since I am using Visual Studio 2019 Version 16.3.4, so I want to use built-in Json support system.text.json, I can’t find how to do the following:

1) Jarray.Parse(json_data)

2) Jarray.Selectokens(json_path_expression)

Since in my real world program, the json data is rather big, usually around 2MB in size, so I need some function with high performance.

However, I didn’t figure out how to use Linq or something else to generate a dictionary Dclose_Date yet.

Please advice.

Continue reading...
 
Back
Top