本篇内容主要讲解“C#中怎么实现JSON功能及对象的序列化和反序列化”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C#中怎么实现JSON功能及对象的序列化和反序列化”吧!
c#中使用json功能,需要Newtonsoft.Json程序包,可以通过NuGet程序包管理器搜索Newtonsoft.Json来安装,也可以在NuGet程序包管理器控制台下使用以下命令来安装:
install-package Newtonsoft.Json
然后引用NewTonSoft.Json命名空间。之后就可以将建立的对象转换为JSON字符串了。
如下创建一个类
public class Student { public int Id { get; set; } public string Name { get; set; } public string Sex { get; set; } public string Description { get; set; } }
生成对象并序列化为JSON字符串
List<Student> students = new List<Student>(); students.Add(new Student { Id = 1, Name = "张三", Sex = "男", Description = "班长" }); students.Add(new Student { Id = 2, Name = "李四", Sex = "女", Description = "小组长" }); students.Add(new Student { Id = 3, Name = "王五", Sex = "男", Description = "宣传委员" }); string studentsJson = JsonConvert.SerializeObject(students); Console.WriteLine(studentsJson);
输出结果:
[{“Id”:1,”Name”:”张三”,”Sex”:”男”,”Description”:”班长”},{“Id”:2,”Name”:”李四”,”Sex”:”女”,”Description”:”小组长”},{“Id”:3,”Name”:”王五”,”Sex”:”男”,”Description”:”宣传委员”}]
有时我们可能不希望某些字段参与对象的JSON序列化,此时可以在该字段上使用[JsonIgnore]特性,对象被序列化后不会包含被忽略的字段
public class Student { public int Id { get; set; } public string Name { get; set; } [JsonIgnore] public string Sex { get; set; } public string Description { get; set; } }
输出结果:
[{“Id”:1,”Name”:”张三”,”Description”:”班长”},{“Id”:2,”Name”:”李四”,”Description”:”小组长”},{“Id”:3,”Name”:”王五”,”Description”:”宣传委员”}]
有时我们可能想在对象序列化时更换字段的输出名称,譬如简化字段名称以缩短JSON字符串的长度,此时可使用[JsonProperty]特性标识字段
public class Student { public int Id { get; set; } public string Name { get; set; } [JsonIgnore] public string Sex { get; set; } [JsonProperty("Desc")] public string Description { get; set; } }
输出结果:
[{“Id”:1,”Name”:”张三”,”Desc”:”班长”},{“Id”:2,”Name”:”李四”,”Desc”:”小组长”},{“Id”:3,”Name”:”王五”,”Desc”:”宣传委员”}]
如果要将生成的JSON字符串以友好的格式化形式输出,可调用以下方法来转换
/// <summary> /// 格式化JSON字符串 /// </summary> /// <param name="str"></param> /// <returns></returns> private static string ConvertJsonString(string str) { JsonSerializer serializer = new JsonSerializer(); TextReader tr = new StringReader(str); JsonTextReader jtr = new JsonTextReader(tr); object obj = serializer.Deserialize(jtr); if (obj != null) { StringWriter textWriter = new StringWriter(); JsonTextWriter jsonWriter = new JsonTextWriter(textWriter) { Formatting = Formatting.Indented, Indentation = 4, IndentChar = ' ' }; serializer.Serialize(jsonWriter, obj); return textWriter.ToString(); } else { return str; } }
于是上面的JSON字符串可改用格式化的形式输出
List<Student> students = new List<Student>(); students.Add(new Student { Id = 1, Name = "张三", Sex = "男", Description = "班长" }); students.Add(new Student { Id = 2, Name = "李四", Sex = "女", Description = "小组长" }); students.Add(new Student { Id = 3, Name = "王五", Sex = "男", Description = "宣传委员" }); //string studentsJson = JsonConvert.SerializeObject(students); string studentsJson = ConvertJsonString(JsonConvert.SerializeObject(students)); Console.WriteLine(studentsJson);
输出结果:
[
{
“Id”: 1,
“Name”: “张三”,
“Desc”: “班长”
},
{
“Id”: 2,
“Name”: “李四”,
“Desc”: “小组长”
},
{
“Id”: 3,
“Name”: “王五”,
“Desc”: “宣传委员”
}
]
以下例子将构建的JSON字符串反序列化为对象,类的定义不要使用以上描述的两个附加特性
public class Student { public int Id { get; set; } public string Name { get; set; } //[JsonIgnore] public string Sex { get; set; } //[JsonProperty("Desc")] public string Description { get; set; } }
string inputJsonString = @"[ { Id: 1, Name: '张三', Sex: '男', Description: '班长' }, { Id: 2, Name: '李四', Sex: '女', Description: '小组长' }, { Id: 3, Name: '王五', Sex: '男', Description: '宣传委员' } ]"; List<Student> objects = JsonConvert.DeserializeObject<List<Student>>(inputJsonString); foreach (Student item in objects) { Console.WriteLine($"Id: {item.Id}, Name: {item.Name}, Sex: {item.Sex}, Description: {item.Description}"); }
输出结果:
Id: 1, Name: 张三, Sex: 男, Description: 班长
Id: 2, Name: 李四, Sex: 女, Description: 小组长
Id: 3, Name: 王五, Sex: 男, Description: 宣传委员
有时候我们可能需要序列化一个对象到字符串,或者反序列化字符串到对象,如对一个类进行封装传输或者存储。这首先需要使用特性[Serializable]将该对象类型标记为可序列化
// 标记类型可序列化 [Serializable] public class Student { public int Id { get; set; } public string Name { get; set; } public string Sex { get; set; } public string Description { get; set; } }
一般对象的序列化和反序列化可以用以下两个方法来实现
/// <summary> /// 序列化对象到字符串 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> private static string Serialize<T>(T obj) { try { IFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, obj); stream.Position = 0; byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Flush(); stream.Close(); return Convert.ToBase64String(buffer); } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <summary> /// 反序列化字符串到对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="str"></param> /// <returns></returns> public static T Deserialize<T>(T obj, string str) { try { obj = default(T); IFormatter formatter = new BinaryFormatter(); byte[] buffer = Convert.FromBase64String(str); MemoryStream stream = new MemoryStream(buffer); obj = (T)formatter.Deserialize(stream); stream.Flush(); stream.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } return obj; }
以下例子使用上述两个方法实现一般对象的序列化和反序列化
List<Student> students = new List<Student>(); students.Add(new Student { Id = 1, Name = "张三", Sex = "男", Description = "班长" }); students.Add(new Student { Id = 2, Name = "李四", Sex = "女", Description = "小组长" }); students.Add(new Student { Id = 3, Name = "王五", Sex = "男", Description = "宣传委员" }); string studentsString = Serialize(students); Console.WriteLine($"序列化后的对象:\n{studentsString}"); List<Student> objects = new List<Student>(); objects = Deserialize(objects, studentsString); Console.WriteLine("反序列化后的对象:"); foreach (Student item in objects) { Console.WriteLine($"Id: {item.Id}, Name: {item.Name}, Sex: {item.Sex}"); }
输出结果:
序列化后的对象:
AAEAAAD/////AQAAAAAAAAAMAgAAAEJDb25zb2xlQXBwMSwgVmVyc2lvbj0xLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPW51bGwEAQAAAHxTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW0NvbnNvbGVBcHAxLlN0dWRlbnQsIENvbnNvbGVBcHAxLCBWZXJzaW9uPTEuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbF1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24EAAAVQ29uc29sZUFwcDEuU3R1ZGVudFtdAgAAAAgICQMAAAADAAAAAwAAAAcDAAAAAAEAAAAEAAAABBNDb25zb2xlQXBwMS5TdHVkZW50AgAAAAkEAAAACQUAAAAJBgAAAAoFBAAAABNDb25zb2xlQXBwMS5TdHVkZW50BAAAABM8SWQ+a19fQmFja2luZ0ZpZWxkFTxOYW1lPmtfX0JhY2tpbmdGaWVsZBQ8U2V4PmtfX0JhY2tpbmdGaWVsZBw8RGVzY3JpcHRpb24+a19fQmFja2luZ0ZpZWxkAAEBAQgCAAAAAQAAAAYHAAAABuW8oOS4iQYIAAAAA+eUtwYJAAAABuePremVvwEFAAAABAAAAAIAAAAGCgAAAAbmnY7lm5sGCwAAAAPlpbMGDAAAAAnlsI/nu4Tplb8BBgAAAAQAAAADAAAABg0AAAAG546L5LqUCQgAAAAGDwAAAAzlrqPkvKDlp5TlkZgL
反序列化后的对象:
Id: 1, Name: 张三, Sex: 男
Id: 2, Name: 李四, Sex: 女
Id: 3, Name: 王五, Sex: 男
到此,相信大家对“C#中怎么实现JSON功能及对象的序列化和反序列化”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。