Share via


How to use Jsonpath in System.text.json

Question

Saturday, October 12, 2019 8:47 PM

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 jsonpath4 = "$..[?(@.Status == 1)].ID";
JArray json_array1 = JArray.Parse(root_json_data);
var status_array1= json_array1.SelectTokens(jsonpath4);

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.

All replies (1)

Sunday, October 13, 2019 7:30 AM ✅Answered

The parser is available in “.NET Core”-based projects, where you can try this:

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}]";
 
 
MyClass[ ] objects = JsonSerializer.Deserialize<MyClass[ ]>( root_json_data );
 
Dictionary<long, DateTime> Dclose_Date;
 
Dclose_Date = objects.Where( o => o.Status == 1 ).ToDictionary( o => o.ID, o => o.CloseDate );
 
. . .
public class MyClass
{
       public long ID { get; set; }
       public int Status { get; set; }
       public DateTime CloseDate { get; set; }
}

 

It is also possible to parse files.

If the data are huge, maybe you should consider other kinds of databases.