将对象转换为 JSON 并将 JSON 转换为 C# 对象
JSON 是服务器和客户端之间更快、更轻量级的数据交换模式。 让我们在演示中看看如何将对象转换为 JSON 并将 JSON 文本转换为 C# 对象。 Nuget 提供了一个名为 JSON.NET 的插件,它提供了转换它的工具。
假设我们有一个员工类,如下所示:
public class Employee
{
public int EmployeeID
{
get;
set;
}
public string EmployeeName
{
get;
set;
}
public string DeptWorking
{
get;
set;
}
public int Salary
{
get;
set;
}
}
我们有一个员工数据列表;我们会将其转换为 JSON 文本。
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace JSON
{
class Program
{
static void Main(string[] args)
{
List < Employee > lstemployee = new List < Employee > ();
lstemployee.Add(new Employee()
{
EmployeeID = 100, EmployeeName = "Pradeep", DeptWorking = "OnLineBanking", Salary = 10000
});
lstemployee.Add(new Employee()
{
EmployeeID = 101, EmployeeName = "Mark", DeptWorking = "OnLineBanking", Salary = 20000
});
lstemployee.Add(new Employee()
{
EmployeeID = 102, EmployeeName = "Smith", DeptWorking = "Mobile banking", Salary = 10000
});
lstemployee.Add(new Employee()
{
EmployeeID = 103, EmployeeName = "John", DeptWorking = "Testing", Salary = 7000
});
string output = JsonConvert.SerializeObject(lstemployee);
Console.WriteLine(output);
Console.ReadLine();
List < Employee > deserializedProduct = JsonConvert.DeserializeObject < List < Employee >> (output);
}
}
}
输出
最终看到了如何将对象转换为 JSON 并将 JSON 转换为对象。