当前位置:首页 > 行业动态 > 正文

C怎样高效读取JSON数组实现数据解析?

在C#中,使用Newtonsoft.Json或System.Text.Json库可读取JSON数组,通过反序列化将JSON数据转为对象集合,定义对应的数据模型类,使用JsonConvert.DeserializeObject方法解析后即可遍历和处理数组元素。

在C#中读取JSON数组是处理数据交互的常见需求,尤其是在与API通信或解析配置文件时,以下分步骤详细说明如何实现这一功能,并确保代码的健壮性和可维护性。


准备工作:安装Newtonsoft.Json库

Newtonsoft.Json(Json.NET)是C#中处理JSON数据的权威库,由James Newton-King开发,被微软官方推荐使用。
通过NuGet安装:

Install-Package Newtonsoft.Json

定义与JSON结构匹配的数据模型

假设需要解析的JSON数组如下:

[
  {
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com"
  },
  {
    "id": 2,
    "name": "Bob",
    "email": "bob@example.com"
  }
]

对应的C#类:

public class User
{
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("email")]
    public string Email { get; set; }
}
  • 关键点:使用[JsonProperty]属性确保字段名称与JSON键匹配,即使命名风格不同(如驼峰式与帕斯卡式)。

从文件或字符串中读取JSON并解析

场景1:从本地文件读取

using Newtonsoft.Json;
using System.IO;
public List<User> ReadUsersFromFile(string filePath)
{
    try
    {
        string json = File.ReadAllText(filePath);
        List<User> users = JsonConvert.DeserializeObject<List<User>>(json);
        return users ?? new List<User>(); // 避免返回null
    }
    catch (FileNotFoundException ex)
    {
        Console.WriteLine($"文件未找到: {ex.Message}");
        return new List<User>();
    }
    catch (JsonException ex)
    {
        Console.WriteLine($"JSON解析失败: {ex.Message}");
        return new List<User>();
    }
}

场景2:从API响应字符串解析

public List<User> ParseUsersFromJsonString(string jsonString)
{
    if (string.IsNullOrEmpty(jsonString))
        return new List<User>();
    try
    {
        return JsonConvert.DeserializeObject<List<User>>(jsonString);
    }
    catch (JsonException ex)
    {
        Console.WriteLine($"解析错误: {ex.Message}");
        return new List<User>();
    }
}

处理复杂或嵌套的JSON结构

若JSON数组包含嵌套对象,

[
  {
    "id": 1,
    "profile": {
      "username": "alice123",
      "age": 30
    }
  }
]

需定义嵌套类:

public class UserProfile
{
    [JsonProperty("username")]
    public string Username { get; set; }
    [JsonProperty("age")]
    public int Age { get; set; }
}
public class User
{
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("profile")]
    public UserProfile Profile { get; set; }
}

异常处理与数据验证

  • 必填字段验证:使用[JsonRequired]标记必须存在的字段。
    public class User
    {
        [JsonProperty("id")]
        [JsonRequired]
        public int Id { get; set; }
    }
  • 类型检查:若JSON数据类型不匹配(如字符串赋值给int属性),会抛出JsonSerializationException,需捕获处理。

性能优化建议

  • 流式读取大文件:使用JsonTextReader逐行解析,减少内存占用。
    using (StreamReader file = File.OpenText("largefile.json"))
    using (JsonTextReader reader = new JsonTextReader(file))
    {
        JsonSerializer serializer = new JsonSerializer();
        List<User> users = serializer.Deserialize<List<User>>(reader);
    }

替代方案:使用System.Text.Json(.NET Core 3.0+)

微软官方库System.Text.Json提供更轻量级的JSON处理方案:

using System.Text.Json;
string json = "[{"id":1}]";
List<User> users = JsonSerializer.Deserialize<List<User>>(json);
  • 优点:性能更高,无需依赖第三方库。
  • 缺点:功能较Json.NET少,例如无[JsonProperty]属性,需通过命名策略匹配字段。

引用说明

  • Newtonsoft.Json官方文档:https://www.newtonsoft.com/json
  • Microsoft System.Text.Json指南:https://docs.microsoft.com/dotnet/standard/serialization/system-text-json-overview
0