c# - 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" } } ]}
谢谢
解决方案
根据您对@Tenretni 答案的评论,我猜您错过了System.Linq
在代码中使用库。
在您的代码中导入System.Collections.Generic
and并使用or子句System.Linq
FirstOrDefault()
.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
推荐阅读
- io - 具有历史支持的 OCaml readline
- c# - 在 WPF 中执行一个函数直到 5 分钟
- json - 使用来自本地 json 文件的 html 中的数据 - typescript, angular 7
- css - 通过 js 悬停时显示工具提示,但在 css 中不显示
- python - TypeError:字符串索引必须是 Django 中的整数
- laravel - 获取关系模型数据
- c# - 如何使用我构建的应用程序从另一台计算机连接到 SQL Server 数据库
- sql - 我想使用“触发器”根据职业提供信息
- c++ - 是否有 gcc 命令可以链接同一目录中的所有 .o 文件并生成 .exe 文件?
- javascript - 将 JavaScript 注入 webView.loadUrl