将 JSON 字符串转换为 C# 对象
本教程将演示如何使用两种不同的方法将 JSON 字符串转换为 C# 对象。
第一个使用 Newtonsoft.Json
库,而第二个使用 JavaScriptSerializer
。这两种方法相似,但使用的语法略有不同,并且需要不同的引用。
使用 Newtonsoft.Json
将 JSON 字符串转换为 C# 对象
Newtonsoft.Json
库是 .NET
的常用 JSON 框架。在将软件包安装到你的解决方案后,可以使用此库。你可以使用带有以下命令的 .NET CLI 来安装软件包。
> dotnet add package Newtonsoft.Json --version 13.0.1
JSON 字符串可以转换为任何类型的 C# 对象,只要它是对象类型的有效 JSON 字符串即可。这是通过反序列化字符串、将其转换为指定类型 (T) 并提供输入 JSON 字符串来完成的。
JsonConvert.DeserializeObject<T>(json_string);
使用 JavaScriptSerializer 将 JSON 字符串转换为 C# 对象
将 JSON 字符串转换为 C# 对象的旧选项是 JavaScriptSerializer
。虽然它没有 Newtonsoft.Json
解决方案那么快,但它仍然可以很好地利用。要使用此方法,你需要在项目中添加对 System.Web.Extensions.dll
的引用。
要添加该引用,请按照以下步骤操作。
- 导航到解决方案资源管理器
- 右键单击引用
-
点击
添加引用
-
单击左侧的
Assemblies
选项卡 -
找到
System.Web.Extensions.dll
文件并单击OK
。
JavaScriptSerializer
的工作方式与 Newtonsoft.Json
方法类似,因为它只需要 JSON 字符串和要反序列化的类型。
JavaScriptSerializer().Deserialize<T>(json_string)
将 JSON 字符串转换为 C# 对象代码示例
下面的代码示例演示了如何使用 JsonConvert.DeserializeObject<T>
和 JavaScriptSerializer
函数将 JSON 字符串转换为任何类型的 C# 对象。对于此示例,我们将字符串转换为包含整数的列表对象 (List<Int32>
) 以及我们在程序中指定的自定义类。
using Newtonsoft.Json;
using System.Data;
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace JSON_To_Object_Example {
class Program {
static void Main(string[] args) {
// Declare the JSON Strings
string list_str = "[1, 2, 3, 9, 8, 7]";
string custom_class_str =
"{ \"Name\":\"John Doe\",\"Age\":21,\"Birthday\":\"2000-01-01T00:00:00\"}";
// ----- Newtonsoft Method -----
// Deserialize the string by specifying the object type
List<Int32> list_converted_ns = JsonConvert.DeserializeObject<List<Int32>>(list_str);
// Print the contents of the newly converted List object to the Console.
Console.WriteLine("Converted List - Newtonsoft: " + String.Join(", ", list_converted_ns) +
"\n");
// The same can be done for any type of C# object, including custom classes. Just change the
// specified Type.
Custom_Class class_converted_ns =
JsonConvert.DeserializeObject<Custom_Class>(custom_class_str);
Console.WriteLine("Converted Class - Newtonsoft:");
PrintPropreties(class_converted_ns);
Console.WriteLine("\n\n");
// ----- JavaScriptSerializer Method -----
// Deserialize the string by specifying the object type
List<Int32> list_converted_js = new JavaScriptSerializer().Deserialize<List<Int32>>(list_str);
Console.WriteLine(
"Converted List - JavaScriptSerializer: " + String.Join(", ", list_converted_js) + "\n");
Custom_Class class_converted_js =
new JavaScriptSerializer().Deserialize<Custom_Class>(custom_class_str);
Console.WriteLine("Converted Class - JavaScriptSerializer:");
PrintPropreties(class_converted_js);
Console.ReadLine();
}
public class Custom_Class {
// Custom Class created for the purposes of this tutorial
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
public static void PrintPropreties(object obj) {
// Uses the System.Component Model to read each property of a class and print its value
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj)) {
string name = descriptor.Name;
object value = descriptor.GetValue(obj);
Console.WriteLine("{0}: {1}", name, value);
}
}
}
}
此代码将输出由逗号连接的整数列表以及转换后的自定义类中的所有属性。你可以观察到两种方法都会产生相同的输出。
输出:
Converted List - Newtonsoft: 1, 2, 3, 9, 8, 7
Converted Class - Newtonsoft:
Name: John Doe
Age: 21
Birthday: 01/01/2000 12:00:00 am
Converted List - JavaScriptSerializer: 1, 2, 3, 9, 8, 7
Converted Class - JavaScriptSerializer:
Name: John Doe
Age: 21
Birthday: 01/01/2000 12:00:00 am
相关文章
在 C# 中将 List<string>转换为字符串
发布时间:2024/03/16 浏览次数:198 分类:编程语言
-
在 C# 中,有两种主要方法可用于将 List
转换为字符串变量,Linq 方法和 String.Join()函数。
在 C# 中将 List<string>转换为字符串
发布时间:2024/03/16 浏览次数:171 分类:编程语言
-
在 C# 中,有两种主要方法可用于将 List
转换为字符串变量,Linq 方法和 String.Join()函数。
在 C# 中将 List<string>转换为字符串
发布时间:2024/03/16 浏览次数:187 分类:编程语言
-
在 C# 中,有两种主要方法可用于将 List
转换为字符串变量,Linq 方法和 String.Join()函数。
在 C# 中发出 HTTP POST Web 请求
发布时间:2024/02/04 浏览次数:131 分类:编程语言
-
在 C# 中,可以使用 3 种主要方法来发出 HTTP POST Web 请求:WebClient 类,HttpWebRequest 类和 HttpClient 类。本教程将讨论在 C# 中发出 HTTP POST Web 请求的方法。使用 C# 中的 WebClient 类发出 HTTP POST Web 请求
在 C# 中运行命令提示符命令
发布时间:2024/02/04 浏览次数:130 分类:编程语言
-
Process 类可用于在 C# 中运行命令提示符命令。在 C# 中使用 Process.Start() 函数运行命令提示符命令
在 C# 中调整图像大小
发布时间:2024/02/04 浏览次数:203 分类:编程语言
-
有两种主要方法可用于在 C# 中调整图像的大小,Bitmap 类构造函数和 graphics.DrawImage()函数。在本教程中,我们将讨论在C#中调整图像大小的方法。我们将带您完成整个过程,从加载原始图像到保
在 C# 中下载图片
发布时间:2024/02/04 浏览次数:138 分类:编程语言
-
有 3 种主要方法可用于下载 C# 中的图片,WebClient.DownloadFile()函数,Bitmap 类和 Image.FromStream()函数。在 C# 中使用 WebClient 类下载图片 WebClient 类提供了用于向 C# 中的 URL 发送数据和从 URL 接收数据
在 C# 中使用秒表
发布时间:2024/02/04 浏览次数:139 分类:编程语言
-
我们可以使用 Stopwatch 类来计算 C# 中的经过时间。使用 C# 中的秒表类计算经过时间 Stopwatch 类在 C# 中准确测量经过的时间。
在 C# 中获取可执行路径
发布时间:2024/02/04 浏览次数:200 分类:编程语言
-
有 3 种主要方法可用于获取 C# 中程序的可执行路径,即 Assembly 类,AppDomain 类和 Path 类。本教程将介绍获取 C# 代码的可执行路径的方法。使用 C# 中的 Assembly 类获取可执行路径