1:JSON工具:Newtonsoft.Json
2:实现方式:通过注解:JsonProperty 中的 PropertyName 属性来实现别名
3:Demo
public class Student
{
[JsonProperty(PropertyName = "ID")]
public int id;
[JsonProperty(PropertyName = "XName")]
public string name;
}
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student()
{
id = 1,
name = "huang"
};
Console.WriteLine(JsonConvert.SerializeObject(stu1));
string jsonStu = @"{""ID"":2,""XName"":""hua""}";
Console.WriteLine("----------------------------");
Student stu2 = JsonConvert.DeserializeObject<Student>(jsonStu);
Console.WriteLine(string.Format("id={0},name={1}", stu2.id, stu2.name));
Console.ReadKey();
}
}

本文介绍如何利用Newtonsoft.Json库中的JsonProperty特性,为C#中的类属性设置JSON序列化时的别名,通过示例展示了如何在序列化和反序列化过程中映射不同的字段名称。

被折叠的 条评论
为什么被折叠?



