龙空技术网

C# 读取自定义的json配置文件的简单例子

凡人兔子张 577

前言:

现时各位老铁们对“c语言json读写库”大概比较着重,兄弟们都想要了解一些“c语言json读写库”的相关内容。那么小编同时在网络上搜集了一些对于“c语言json读写库””的相关文章,希望朋友们能喜欢,各位老铁们一起来学习一下吧!

在C#中,您可以使用System.Text.JsonNewtonsoft.Json库来读取JSON配置文件的内容。

以下是使用这两个库的示例代码:

使用System.Text.Json库:

using System;using System.IO;using System.Text.Json;public class Program{    public static void Main()    {        string jsonFilePath = "config.json";        // 读取JSON文件内容        string jsonContent = File.ReadAllText(jsonFilePath);        // 解析JSON内容        JsonDocument jsonDocument = JsonDocument.Parse(jsonContent);        // 获取根元素        JsonElement root = jsonDocument.RootElement;        // 读取配置项        string value = root.GetProperty("key").GetString();        Console.WriteLine(value);    }}

使用Newtonsoft.Json库:

using System;using System.IO;using Newtonsoft.Json.Linq;public class Program{    public static void Main()    {        string jsonFilePath = "config.json";        // 读取JSON文件内容        string jsonContent = File.ReadAllText(jsonFilePath);        // 解析JSON内容        JObject jsonObject = JObject.Parse(jsonContent);        // 读取配置项        string value = jsonObject["key"].ToString();        Console.WriteLine(value);    }}

在这两个示例中,我们首先使用File.ReadAllText方法读取JSON文件的内容。

然后,使用JsonDocument.Parse方法(对于System.Text.Json)或JObject.Parse方法(对于Newtonsoft.Json)解析JSON内容。

接下来,我们可以使用相应的API来读取JSON配置项的值。

请确保在使用这些方法之前,您已经添加了对System.Text.JsonNewtonsoft.Json命名空间的引用,并且已经安装了相应的库。

标签: #c语言json读写库