如何使用JsonPath使用C#示例?

时间:2011-09-24 06:17:17

标签: c# jsonpath

我正在尝试使用JsonPath for .NET(http://code.google.com/p/jsonpath/downloads/list)而我找不到如何解析Json字符串和JsonPath字符串并获得结果的示例。

有没有人用过这个?

3 个答案:

答案 0 :(得分:23)

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

JsonPath的工作方式是使用名为IJsonPathValueSystem的接口来遍历解析的Json对象。 JsonPath附带了一个内置的BasicValueSystem,它使用IDictionary接口来表示Json对象,使用IList接口来表示Json数组。

您可以通过使用C#集合初始化程序构建它们来创建自己的BasicValueSystem兼容的Json对象,但是当您的Json以远程服务器的字符串形式进入时,这没什么用处。

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

不幸的是,Json.NET没有将Json字符串反序列化为与BasicValueSystem兼容的格式。因此,使用JsonPath和Json.NET的第一个任务是编写一个JsonNetValueSystem来实现IJsonPathValueSystem并且理解JObject个对象,JArray数组和{{1} } JValue生成的值。

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

JObject.Parse

现在我们可以编写一个示例JsonPath程序,其中包含所有三个

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;
    }
}

产生这个输出:

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();
    }
}

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

答案 1 :(得分:2)

对于那些不喜欢LINQ(.NET 2.0)的人:

namespace JsonPath
{


    public sealed class JsonNetValueSystem : IJsonPathValueSystem
    {


        public bool HasMember(object value, string member)
        {
            if (value is Newtonsoft.Json.Linq.JObject)
            {
                // return (value as JObject).Properties().Any(property => property.Name == member);

                foreach (Newtonsoft.Json.Linq.JProperty property in (value as Newtonsoft.Json.Linq.JObject).Properties())
                {
                    if (property.Name == member)
                        return true;
                }

                return false;
            }

            if (value is Newtonsoft.Json.Linq.JArray)
            {
                int index = ParseInt(member, -1);
                return index >= 0 && index < (value as Newtonsoft.Json.Linq.JArray).Count;
            }
            return false;
        }


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


        public System.Collections.IEnumerable GetMembers(object value)
        {
            System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();

            var jobject = value as Newtonsoft.Json.Linq.JObject;
            /// return jobject.Properties().Select(property => property.Name);

            foreach (Newtonsoft.Json.Linq.JProperty property in jobject.Properties())
            { 
                ls.Add(property.Name);
            }

            return ls;
        }


        public bool IsObject(object value)
        {
            return value is Newtonsoft.Json.Linq.JObject;
        }


        public bool IsArray(object value)
        {
            return value is Newtonsoft.Json.Linq.JArray;
        }


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

            return value is Newtonsoft.Json.Linq.JObject || value is Newtonsoft.Json.Linq.JArray ? false : true;
        }


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


    }


}

用法:

object obj = Newtonsoft.Json.JsonConvert.DeserializeObject(input);

JsonPath.JsonPathContext context = new JsonPath.JsonPathContext { ValueSystem = new JsonPath.JsonNetValueSystem() };

foreach (JsonPath.JsonPathNode node in context.SelectNodes(obj, "$.store.book[*].author"))
{
    Console.WriteLine(node.Value);
}

答案 2 :(得分:0)

使用Newtonsoft.Json.Linq可以使用功能SelectToken并尝试使用JsonPath 查看文档https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm

Object jsonObj = JObject.Parse(stringResult);

JToken pathResult = jsonObj.SelectToken("results[0].example");

return pathResult.ToString();