0
点赞
收藏
分享

微信扫一扫

C#上位机开发(十七)—— 基于NuGet安装并使用包(Visual Studio)


一、NuGet

微软官方文档:​​https://docs.microsoft.com/zh-cn/nuget/​​。

NuGet 是适用于 .NET 的包管理器。 它使开发人员能够创建、共享和使用有用的 .NET 库。 NuGet 客户端工具可生成这些库并将其作为“包”。

C#上位机开发(十七)—— 基于NuGet安装并使用包(Visual Studio)_c#

二、添加 Newtonsoft.Json Nuget 包

1. 创建项目

可将 NuGet 包安装到任何 .NET 项目,前提是包支持与项目相同的目标框架。

C#上位机开发(十七)—— 基于NuGet安装并使用包(Visual Studio)_包管理器_02

2. NuGet 程序包管理器

(1)在解决方案资源管理器中,右键单击“引用”,选择“管理 NuGet 包” 。

C#上位机开发(十七)—— 基于NuGet安装并使用包(Visual Studio)_NuGet_03

(2)将“nuget.org”选择为“包源”,选择“浏览”选项卡并搜索“Newtonsoft.Json”,在列表中选择该包,然后选择“安装” 。

C#上位机开发(十七)—— 基于NuGet安装并使用包(Visual Studio)_NuGet_04

(3)接受任何许可证提示。

(4)安装完成之后,如图。

C#上位机开发(十七)—— 基于NuGet安装并使用包(Visual Studio)_.net_05

三、在应用中使用 Newtonsoft.Json API

使用项目中的 Newtonsoft.Json 包,可调用 JsonConvert.SerializeObject 方法将对象转换为可人工读取的字符串。

1. 编写代码

public class Account
{
public string Name { get; set; }
public string Email { get; set; }
public DateTime DOB { get; set; }
}

添加引用:

using Newtonsoft.Json;

编写按钮回调函数:

private void button1_Click(object sender, EventArgs e)
{
Account account = new Account
{
Name = "John Doe",
Email = "john@microsoft.com",
DOB = new DateTime(1980, 2, 20, 0, 0, 0, DateTimeKind.Utc),
};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
textBox1.Text = json;
}

2. 运行结果

C#上位机开发(十七)—— 基于NuGet安装并使用包(Visual Studio)_json_06



举报

相关推荐

0 条评论