I’m trying to use JsonPath for .NET (http://code.google.com/p/jsonpath/downloads/list) and I’m having trouble finding an example of how to parse a Json string and a JsonPath string and get a result.
Has anyone used this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The problem you are experiencing is that the C# version of JsonPath does not include a Json parser so you have to use it with another Json framework that handles serialization and deserialization.
The way JsonPath works is to use an interface called
IJsonPathValueSystemto traverse parsed Json objects. JsonPath comes with a built-inBasicValueSystemthat uses theIDictionaryinterface to represent Json objects and theIListinterface to represent Json arrays.You can create your own
BasicValueSystem-compatible Json objects by constructing them using C# collection initializers but this is not of much use when your Json is coming in in the form of strings from a remote server, for example.So if only you could take a Json string and parse it into a nested structure of
IDictionaryobjects,IListarrays, and primitive values, you could then use JsonPath to filter it! As luck would have it, we can use Json.NET which has good serialization and deserialization capabilities to do that part of the job.Unfortunately, Json.NET does not deserialize Json strings into a format compatible with the
BasicValueSystem. So the first task for using JsonPath with Json.NET is to write aJsonNetValueSystemthat implementsIJsonPathValueSystemand that understands theJObjectobjects,JArrayarrays, andJValuevalues thatJObject.Parseproduces.So download both JsonPath and Json.NET and put them into a C# project. Then add this class to that project:
Now with all three of these pieces we can write a sample JsonPath program:
which produces this output:
This example is based on the Javascript sample at the JsonPath site: