如何使用JsonPath使用C#示例? [英] How to use C# example using JsonPath?

查看:400
本文介绍了如何使用JsonPath使用C#示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JsonPath用于.NET( http://code.google .com / p / jsonpath / downloads / list ),而我在查找如何解析Json字符串和JsonPath字符串并获得结果的示例时遇到了麻烦。

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.

有人用过吗?

推荐答案

您遇到的问题是JsonPath的C#版本不包含Json解析器,因此您必须将其与另一个处理序列化和反序列化的Json框架一起使用。

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.

JsonPath的工作方式是使用名为 IJsonPathValueSystem 的接口遍历已解析的Json对象。 JsonPath带有内置的 BasicValueSystem ,该接口使用 IDictionary 接口表示Json对象和 IList 接口代表Json数组。

The way JsonPath works is to use an interface called IJsonPathValueSystem to traverse parsed Json objects. JsonPath comes with a built-in BasicValueSystem that uses the IDictionary interface to represent Json objects and the IList interface to represent Json arrays.

您可以创建自己的 BasicValueSystem -通过使用C#集合初始化器构造对象来兼容Json对象,但是当您的Json以来自远程服务器的字符串形式出现时,这并没有太大用处。

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.

因此,只要您可以将Json字符串解析为 IDictionary 对象, IList 数组的嵌套结构,和原始值,然后可以使用JsonPath对其进行过滤!幸运的是,我们可以使用具有良好的序列化和反序列化功能的Json.NET来完成那部分工作。

So if only you could take a Json string and parse it into a nested structure of IDictionary objects, IList arrays, 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.

不幸的是,Json.NET不会反序列化Json字符串转换为与 BasicValueSystem 兼容的格式。因此,将JsonPath与Json.NET结合使用的首要任务是编写一个 JsonNetValueSystem ,该实现实现 IJsonPathValueSystem 并理解 JObject 对象, JArray 数组和 JValue JObject.Parse 生成。

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 a JsonNetValueSystem that implements IJsonPathValueSystem and that understands the JObject objects, JArray arrays, and JValue values that JObject.Parse produces.

因此,请同时下载JsonPath和Json.NET并将它们放入C#项目中。然后将此类添加到该项目:

So download both JsonPath and Json.NET and put them into a C# project. Then add this class to that project:

public sealed class JsonNetValueSystem : IJsonPathValueSystem
{
    public bool HasMember(object value, string member)
    {
        if (value is JObject)
                return (value as JObject).Properties().Any(property => property.Name == member);
        if (value is JArray)
        {
            int index = ParseInt(member, -1);
            return index >= 0 && index < (value as JArray).Count;
        }
        return false;
    }

    public object GetMemberValue(object value, string member)
    {
        if (value is JObject)
        {
            var memberValue = (value as JObject)[member];
            return memberValue;
        }
        if (value is JArray)
        {
            int index = ParseInt(member, -1);
            return (value as JArray)[index];
        }
        return null;
    }

    public IEnumerable GetMembers(object value)
    {
        var jobject = value as JObject;
        return jobject.Properties().Select(property => property.Name);
    }

    public bool IsObject(object value)
    {
        return value is JObject;
    }

    public bool IsArray(object value)
    {
        return value is JArray;
    }

    public bool IsPrimitive(object value)
    {
        if (value == null)
            throw new ArgumentNullException("value");

        return value is JObject || value is JArray ? false : true;
    }

    private int ParseInt(string s, int defaultValue)
    {
        int result;
        return int.TryParse(s, out result) ? result : defaultValue;
    }
}

现在所有 3 在这些片段中,我们可以编写一个示例JsonPath程序:

Now with all three of these pieces we can write a sample JsonPath program:

class Program
{
    static void Main(string[] args)
    {
        var input = @"
              { ""store"": {
                    ""book"": [ 
                      { ""category"": ""reference"",
                            ""author"": ""Nigel Rees"",
                            ""title"": ""Sayings of the Century"",
                            ""price"": 8.95
                      },
                      { ""category"": ""fiction"",
                            ""author"": ""Evelyn Waugh"",
                            ""title"": ""Sword of Honour"",
                            ""price"": 12.99
                      },
                      { ""category"": ""fiction"",
                            ""author"": ""Herman Melville"",
                            ""title"": ""Moby Dick"",
                            ""isbn"": ""0-553-21311-3"",
                            ""price"": 8.99
                      },
                      { ""category"": ""fiction"",
                            ""author"": ""J. R. R. Tolkien"",
                            ""title"": ""The Lord of the Rings"",
                            ""isbn"": ""0-395-19395-8"",
                            ""price"": 22.99
                      }
                    ],
                    ""bicycle"": {
                      ""color"": ""red"",
                      ""price"": 19.95
                    }
              }
            }
        ";
        var json = JObject.Parse(input);
        var context = new JsonPathContext { ValueSystem = new JsonNetValueSystem() };
        var values = context.SelectNodes(json, "$.store.book[*].author").Select(node => node.Value);
        Console.WriteLine(JsonConvert.SerializeObject(values));
        Console.ReadKey();
    }
}

会产生以下输出:

["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]

此示例基于JsonPath站点上的Javascript示例:

This example is based on the Javascript sample at the JsonPath site:

  • Javascript Usage and Example

这篇关于如何使用JsonPath使用C#示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆