我最近发表了一些文章来解释如何使用Newtonsoft.Json框架。如果你想了解更多,一定要去看看。在本文中,我将告诉您如何在NewtonSoft.Json中使用JsonSerializer。
有时候,Newtonsoft.Json框架中的JsonConvert类可能无法满足您的需求。
JsonSerializer
JsonSerializer是在JSON文本和.NET对象之间进行转换的最快方法。它通过将.NET对象属性名称映射到JSON属性名称并复制值,将.NET对象转换为其JSON等效对象并再次转换。它还为处理JSON数据提供了更多的控制和性能优势。
我在VS2015中使用一个控制台应用程序作为我的IDE。
让我们看看最简单的代码,我们可以编写这些代码来使用JsonSerializer将对象转换为JSON并将JSON数据写入系统上的文件。
class Program { static void Main(string[] args) { Console.Clear(); Author author = new Author { name = "Sid", since = new DateTime(2015, 11, 25) }; Console.WriteLine("No settings"); var serializer = new JsonSerializer(); using (var sw = new StreamWriter(@"..\..\noparameters.json")) { using (var writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, author); } } } }
上面的代码非常简单。我正在创建Author类型的对象和JsonSerializer类型的serializer对象。接下来,由于我们希望在系统上的文件中写入一些内容,所以我使用StreamWriter类。
这里的重要类是JsonTextWriter,它是一个提供生成JSON数据的快速、非缓存、仅向前的方法的writer。该类与StreamWriter对象一起工作,然后在对序列化程序调用序列化方法时使用,该序列化程序实际将author对象序列化为文件。
此程序的输出如下所示:
{"name":"Sid","courses":null,"since":"2015-11-25T00:00:00","happy":false,"issues":null,"car":null}
Indented JSON
正如上面的输出一样,它都在一行中,如果对象有许多成员,则很难读取。现在让我们使用Formatting.Indented将缩进格式添加到序列化程序中,以便文件中的输出易于读取。
class Program { static void Main(string[] args) { Console.Clear(); Author author = new Author { name = "Sid", since = new DateTime(2015, 11, 25) }; Console.WriteLine("With Indentation"); var serializer = new JsonSerializer { Formatting = Formatting.Indented }; using (var sw = new StreamWriter(@"..\..\indented-data.json")) { using (var writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, author); } } } }
该程序的输出格式良好,易于阅读:
{
"name": "Sid",
"courses": null,
"since": "2015-11-25T00:00:00",
"happy": false,
"issues": null,
"car": null
}
Null 值
正如您在上面的输出中看到的,JSON中也存在具有空值的成员。如果正在处理跨平台应用程序,则应考虑忽略序列化时的空值。对于复杂的对象,JSON数据的大小会更大,然后需要通过wire发送给您的客户机。
让我们看看如何通过使用NullValueHandling.Ignore配置序列化程序设置:
class Program { static void Main(string[] args) { Console.Clear(); Author author = new Author { name = "Sid", since = new DateTime(2015, 11, 25) }; Console.WriteLine("Ignore nulls"); var serializer = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented }; using (var sw = new StreamWriter(@"..\..\without-nulls.json")) { using (var writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, author); } } } }
这个程序的输出非常小,如下所示:
{
"name": "Sid",
"since": "2015-11-25T00:00:00",
"happy": false
}
这个框架非常适合处理JSON数据和.NET对象。查看我其他关于Newtonsoft.Json框架的文章。我希望这篇文章能解释如何在Newtonsoft.Json框架中正确使用JsonSerializer。