【问题标题】:how to valilidate a condtion for list in JSON object in C#如何在 C# 中验证 JSON 对象中列表的条件
【发布时间】:2020-09-23 19:53:28
【问题描述】:

我有一个 JSON 文件,我必须在其中执行基于 json 元素的数据验证。

下面是我的json文件

[
  {
    "id": "5241585099662481339",
    "displayName": "Music",
    "name": "music",
    "slug": "music",
    "imageUrl": "http://mno.com"
  },
  {
    "id": "6953585193220490118",
    "displayName": "Celebrities",
    "name": "celebrities",
    "slug": "celebrities",
    "imageUrl": "http://ijk.com"
  },
  {
    "id": "5757029936226020304",
    "displayName": "Entertainment",
    "name": "entertainment",
    "slug": "entertainment",
    "imageUrl": "http://pqr.com"
  },
  {
    "id": "3718",
    "displayName": "Saturday Night Live",
    "name": "saturday night live",
    "slug": "saturday-night-live",
    "imageUrl": "http://efg.com"
  },
  {
    "id": "8113008320053776960",
    "displayName": "Hollywood",
    "name": "hollywood",
    "slug": "hollywood",
    "imageUrl": "http://qwe.com"
  }
]

下面是代码sn-p

var list = JsonConvert.DeserializeObject<List<MyItem>>(json);

    if (list.Any(e => e.id =="3718")) 
    {
        //How do get the exact displayName on the if condtion 
    }    

    public class MyItem
    {
        public string id;
        public string displayName;
        public string name;
        public string slug;
        public string imageUrl;
    }

这里我想要基于 if 条件通过的 displayname 值。所以在我的 if 循环中 if put list.displayname 我需要将值打印为 Saturday Night Live

【问题讨论】:

    标签: c# .net json .net-framework-version jsonserializer


    【解决方案1】:
    // name will be null if there isn't any item where id == 3718
    var name = list.FirstOrDefault(item => string.Equals(item.id, "3718"))?.displayName;
    
    // InvalidOperationException will be  thrown if there isn't any item where id == 3718
    var name = list.First(item => string.Equals(item.id, "3718")).displayName;
    

    【讨论】:

      【解决方案2】:

      检查一下:

      var name = list.Where(e=>e.id=="3718").Select(x=>x.displayName);
      

      【讨论】:

        猜你喜欢
        • 2021-10-23
        • 1970-01-01
        • 2021-05-18
        • 2017-10-20
        • 2015-11-09
        • 1970-01-01
        • 1970-01-01
        • 2015-03-24
        • 1970-01-01
        相关资源
        最近更新 更多