C# linq 查询json

假如json是动态变化的,则可通过以下方式做

string json = @"{
                        ""count"": 3,
                        ""value"": [
                          {
                            ""id"": ""AAAAAAAAAAAAA"",
                            ""description"": ""test1"",
                            ""name"": ""name1""
                          },
                          {
                            ""id"": ""BBBBBBBBBB"",
                            ""description"": ""test2"",
                            ""name"": ""name2""
                          },
                          {
                            ""id"": ""CCCCCCCCCCCC"",
                            ""description"": ""test3"",
                            ""name"": ""name3""
                          }
                        ]
                        }";

            var test = JsonConvert.DeserializeObject<JObject>(json);
var code = test ["code"].Value<int>();
            string value = test["value"][1].ToString();

假如是规范的,可以反序列化为C#对象,在进行解析

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft;
using Newtonsoft.Json.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {

            string json = @"{
                        ""count"": 3,
                        ""value"": [
                          {
                            ""id"": ""AAAAAAAAAAAAA"",
                            ""description"": ""test1"",
                            ""name"": ""name1""
                          },
                          {
                            ""id"": ""BBBBBBBBBB"",
                            ""description"": ""test2"",
                            ""name"": ""name2""
                          },
                          {
                            ""id"": ""CCCCCCCCCCCC"",
                            ""description"": ""test3"",
                            ""name"": ""name3""
                          }
                        ]
                        }";

            var test = JsonConvert.DeserializeObject<Content>(json);

            Value value = test.Values.FirstOrDefault(x => x.Name.Equals("name1", StringComparison.InvariantCultureIgnoreCase));

        }
    }

    public class Content
    {
        [JsonProperty("count")]
        public int Count { get; set; }

        [JsonProperty("value")]
        public List<Value> Values { get; set; }

        public Content()
        {
            Values = new List<Value>();
        }
    }

    public class Value
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }
    }

}


版权声明:本文为weixin_43632687原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。