在C#中从TextBox搜索JSON文件中的数据

时间:2019-01-07 17:59:14

标签: c# json winforms

这是我的json文件内容

[
  {
    "FirstName": "Shubham",
    "LastName": "Singh",
    "MiddleName": "",
    "EnrollmentDate": "6/01/2019",
    "AssignedCourse": "Python",
    "RollNumber": "SSCou1666",
    "AssignedTeacher": "XYZ",
    "ContactNumber": "100"
  },
  {
    "FirstName": "Shivang",
    "LastName": "Singh",
    "MiddleName": "Rathod",
    "EnrollmentDate": "7/01/2019",
    "AssignedCourse": "French",
    "RollNumber": "SSCou6479",
    "AssignedTeacher": "ABC",
    "ContactNumber": "600"
  }
]

我的目标是在C#winforms的文本框中按名称搜索特定记录。我无法理解如何首先针对特定名称或卷号在JSON中搜索特定记录。甚至可以在JSON中实现吗?

1 个答案:

答案 0 :(得分:0)

使用NewtownSoft.Json,可以将JSON数组反序列化为List<object>,然后使用任何类对象的Properties过滤列表。

例如,使用特定的RollNumber值过滤列表:

string JSONObject = [Your JSON string]
var allStudents = JsonConvert.DeserializeObject<List<Student>>(JSONObject);

string rollNumberValue = textBox1.Text;

//Filter the list using a property value
var specificStudent = allStudents.FirstOrDefault(s => s.RollNumber == rollNumberValue);

用作容器的Student类:

public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public string EnrollmentDate { get; set; }
    public string AssignedCourse { get; set; }
    public string RollNumber { get; set; }
    public string AssignedTeacher { get; set; }
    public string ContactNumber { get; set; }
}