根据 JSON 中的条件获取列数

问题描述 投票:0回答:1

要求是根据 JSON 字符串内的条件获取列数

string jsonString = @"{'data': 'name = sam, age = 51, name = joe, age = 62, name = ross, age = 45'}";

条件年龄>=50

年龄计数 = 2

选项1

我尝试先将 JSON 反序列化为模型

public class JsonModel
{
    public string Name { get; set; }

    public int Age { get; set; }
}

var resultList = JsonConvert.DeserializeObject<JsonModel>(s);

List<JsonModel> result = items.Where(x => x.Age >= 50).ToList();// doesnt work

Console.WriteLine(result.Count());

选项2

        dynamic obj = JObject.Parse(s);
        var a = obj.data[0]; //Cannot access child value on Newtonsoft.Json.Linq.JValue.'
        string error = a.age;

选项3

dynamic obj = JObject.Parse(s);
    var a = obj.data["age"]; //Cannot access child value on Newtonsoft.Json.Linq.JValue.'
    

尝试了几个选项都不起作用,我如何获得计数?

选项4

static async Task Main(string[] args)
    {
       
        HttpClient client = new HttpClient();
        var s = await client.GetStringAsync("https://coderbyte.com/api/challenges/json/age-counting");
        var jsonLinq = JObject.Parse(s);


 foreach (var package in jsonLinq)
        {
            string[] values = package.Value.ToString().Split(',');
            //var res = values.Where(String.Format("age=50"));

            List<string> list = new List<string>();
            list.AddRange(values);
            
        }
           }
c# .net linq json.net
1个回答
0
投票

您应该拆分

data
属性字符串值并自行解析。

var parsed = JsonDocument.Parse(jsonStr);
var dataString = parsed.RootElement.GetProperty("data").GetString();

if (dataString != null)
{
    var pairs = dataString.Split(", ").Chunk(2);

    var items = pairs.Select(p =>
        {
            var dictionary = p.Select(x => x.Split("=", StringSplitOptions.TrimEntries))
                .Where(x => x.Length == 2).ToDictionary(x => x[0], x => x[1]);
            if (!dictionary.ContainsKey("key") || !dictionary.ContainsKey("age"))
                return default!;

            return new
            {
                Key = dictionary["key"],
                Age = int.Parse(dictionary["age"])
            };
        })
        .Where(v => v != null)
        .ToList();

    var count = items.Count(x => x.Age >= 50);
}
© www.soinside.com 2019 - 2024. All rights reserved.