C#怎么解析复杂的JSON格式接口数据

发布时间:2021-06-17 11:50:33 作者:小新
来源:亿速云 阅读:591
# C#怎么解析复杂的JSON格式接口数据

## 引言

在现代软件开发中,JSON(JavaScript Object Notation)已成为前后端数据交互的主流格式。C#作为.NET平台的核心语言,提供了多种强大的工具来解析和处理复杂JSON数据。本文将详细介绍使用`System.Text.Json`和`Newtonsoft.Json`两种主流方案解析嵌套结构、动态字段等复杂JSON数据的实践方法。

---

## 一、基础概念与准备工作

### 1.1 复杂JSON的典型结构
复杂JSON通常包含以下特征:
- 多级嵌套对象/数组
- 动态变化的字段名
- 混合数据类型字段
- 特殊格式(如日期、二进制数据)

示例数据:
```json
{
  "orderId": "20230815-001",
  "customer": {
    "name": "张三",
    "contacts": [
      { "type": "phone", "value": "13800138000" },
      { "type": "email", "value": "zhangsan@example.com" }
    ]
  },
  "items": [
    {
      "sku": "ITEM-1001",
      "quantity": 2,
      "price": 49.99
    }
  ],
  "metadata": {
    "createdAt": "2023-08-15T10:00:00Z",
    "tags": ["urgent", "vip"]
  }
}

1.2 环境准备

// .NET项目添加NuGet包
// System.Text.Json(.NET Core 3.0+内置)
dotnet add package System.Text.Json

// 或 Newtonsoft.Json
dotnet add package Newtonsoft.Json

二、使用System.Text.Json解析

2.1 定义模型类(推荐方式)

public class Order
{
    public string OrderId { get; set; }
    public Customer Customer { get; set; }
    public List<OrderItem> Items { get; set; }
    public Dictionary<string, object> Metadata { get; set; }
}

public class Customer 
{
    public string Name { get; set; }
    public List<Contact> Contacts { get; set; }
}

// 其他嵌套类...

2.2 反序列化操作

string json = File.ReadAllText("order.json");
var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    Converters = { new JsonStringEnumConverter() }
};

Order order = JsonSerializer.Deserialize<Order>(json, options);

2.3 处理动态字段

// 使用JsonElement处理未知结构
if (order.Metadata.TryGetValue("tags", out var tags))
{
    if (tags.ValueKind == JsonValueKind.Array)
    {
        foreach (var tag in tags.EnumerateArray())
        {
            Console.WriteLine(tag.GetString());
        }
    }
}

三、使用Newtonsoft.Json解析

3.1 动态类型处理

dynamic dynamicOrder = JObject.Parse(json);
Console.WriteLine(dynamicOrder.customer.name);

// 访问数组
foreach (var contact in dynamicOrder.customer.contacts)
{
    Console.WriteLine($"{contact.type}: {contact.value}");
}

3.2 自定义转换器

处理特殊日期格式:

public class CustomDateTimeConverter : JsonConverter<DateTime>
{
    public override DateTime ReadJson(...)
    {
        return DateTime.ParseExact(reader.Value.ToString(), 
               "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
    }
}

var settings = new JsonSerializerSettings
{
    Converters = new List<JsonConverter> { new CustomDateTimeConverter() }
};

四、高级场景处理

4.1 处理多态类型

[JsonDerivedType(typeof(PhoneContact), "phone")]
[JsonDerivedType(typeof(EmailContact), "email")]
public abstract class ContactBase { /*...*/ }

public class PhoneContact : ContactBase { /*...*/ }

4.2 大文件流式处理

using var stream = new FileStream("large.json", FileMode.Open);
using var reader = new Utf8JsonReader(stream);

while (reader.Read())
{
    if (reader.TokenType == JsonTokenType.PropertyName 
        && reader.GetString() == "orderId")
    {
        reader.Read();
        Console.WriteLine(reader.GetString());
    }
}

五、性能优化建议

  1. 模型复用:缓存Type信息避免反射开销
  2. 源生成器:.NET 6+可使用JsonSourceGenerator
  3. 异步操作:对于大文件使用DeserializeAsync
  4. 合理选择库
    • System.Text.Json:性能更高,内存占用少
    • Newtonsoft.Json:功能更全面

六、常见问题排查

  1. 属性映射失败

    • 检查大小写策略
    • 使用[JsonPropertyName("customName")]特性
  2. 日期格式异常

    options.Converters.Add(new DateTimeConverterUsingDateTimeParse());
    
  3. 循环引用

    options.ReferenceHandler = ReferenceHandler.Preserve;
    

结语

通过合理选择工具和模式,C#可以优雅地处理各种复杂JSON结构。建议: - 简单场景优先使用System.Text.Json - 需要动态特性时选择Newtonsoft.Json - 关键路径考虑使用源生成器提升性能

完整示例代码:https://github.com/example/json-parsing-demo “`

(注:实际字数约1500字,可根据需要删减部分章节调整到1200字左右)

推荐阅读:
  1. Oracle解析复杂json的方法
  2. Flink SQL解析Json格式数据的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

json

上一篇:.net core日志结构化的含义和用法

下一篇:SpringBoot中banner如何使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》