首页 > 解决方案 > C#反序列化json并查找

问题描述

我怎样才能在这个列表中找到一个特定的 id?

var contactList = JsonConvert.DeserializeObject<ContactList>(jsonString);

contactList.contacts.FindAll(x => x.id == item.id);

上面的代码没有按 id 过滤,而是从对象返回所有行。

(Visual Studio 没有向我显示 .Where 子句仅 .Find 和 .FindAll)

C# 代码

namespace RestDemo.Model 
{ 
   public class Phone 
   { 
      public string mobile { get; set; } 
      public string home { get; set; } 
      public string office { get; set; } 
   } 

   public class Contact 
   { 
      public int id { get; set; } 
      public string name { get; set; } 
      public string email { get; set; } 
      public string address { get; set; } 
      public string gender { get; set; } 
      public Phone phone { get; set; } 
   } 

   public class ContactList 
   { 
      public List<Contact> contacts { get; set; } 
   } 
}

杰森:

{ "contacts": [     {           "id": 200,          "name": "Ravi Tamada",          "email": "ravi@gmail.com",          "address": "xx-xx-xxxx,x - street, x - country",            "gender": "male",           "phone": {              "mobile": "+91 0000000000",             "home": "00 000000",                "office": "00 000000"           }       },      {           "id": 201,          "name": "Klev Krist",           "email": "klev@gmail.com",          "address": "xx-xx-xxxx,x - street, x - country",            "gender": "male",           "phone": {              "mobile": "+91 0000000000",             "home": "00 000000",                "office": "00 000000"           }       },      {           "id": 202,          "name": "Paul Neil",            "email": "paul.neil@gmail.com",         "address": "xx-xx-xxxx,x - street, x - country",            "gender": "male",           "phone": {              "mobile": "+91 0000000000",             "home": "00 000000",                "office": "00 000000"           }       }   ]}

谢谢

标签: c#jsonlinqobjectjson-deserialization

解决方案


根据您对@Tenretni 答案的评论,我猜您错过了System.Linq在代码中使用库。

在您的代码中导入System.Collections.Genericand并使用or子句System.LinqFirstOrDefault().Where()

using System.Collections.Generic;
using System.Linq;

//…

string jsonString = @"{ 'contacts': [{ 'id': 'c200', 'name': 'Ravi Tamada', 'email': 'ravi@gmail.com', 'address': 'xx-xx-xxxx,x - street, x - country', 'gender': 'male', 'phone': { 'mobile': '+91 0000000000', 'home': '00 000000', 'office': '00 000000' } }] }";

var contactList = JsonConvert.DeserializeObject<ContactList>(jsonString);
var item = "c200";
var result = contactList.contacts.FirstOrDefault(x => x.id == item);
Console.WriteLine(result.name);

//If you have multiple records with same ID then you can try where clause
var result = contactList.contacts.Where(x => x.id == item);      //Here result will be list of Contact

.Net 小提琴


推荐阅读