C#中实现JSON功能及对象的序列化和反序列化

Newtonsoft.Json程序包的引用

c#中使用json功能,需要Newtonsoft.Json程序包,可以通过NuGet程序包管理器搜索Newtonsoft.Json来安装,也可以在NuGet程序包管理器控制台下使用以下命令来安装:

install-package Newtonsoft.Json

然后引用NewTonSoft.Json命名空间。之后就可以将建立的对象转换为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 students = new List();

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”:”宣传委员”}]

使用[JsonIgnore]特性忽略字段的序列化

有时我们可能不希望某些字段参与对象的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”:”宣传委员”}]

使用[JsonProperty]特性标识字段的序列化名称

有时我们可能想在对象序列化时更换字段的输出名称,譬如简化字段名称以缩短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字符串

如果要将生成的JSON字符串以友好的格式化形式输出,可调用以下方法来转换

///

/// 格式化JSON字符串

///

///

///

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 students = new List();

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字符串的反序列化

以下例子将构建的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 objects = JsonConvert.DeserializeObject>(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; }

}

一般对象的序列化和反序列化可以用以下两个方法来实现

///

/// 序列化对象到字符串

///

///

///

///

private static string Serialize(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);

    }

}

///

/// 反序列化字符串到对象

///

///

///

///

///

public static T Deserialize(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 students = new List();

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 objects = new List();

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功能及对象的序列化和反序列化)