您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 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"]
}
}
// .NET项目添加NuGet包
// System.Text.Json(.NET Core 3.0+内置)
dotnet add package System.Text.Json
// 或 Newtonsoft.Json
dotnet add package Newtonsoft.Json
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; }
}
// 其他嵌套类...
string json = File.ReadAllText("order.json");
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
};
Order order = JsonSerializer.Deserialize<Order>(json, options);
// 使用JsonElement处理未知结构
if (order.Metadata.TryGetValue("tags", out var tags))
{
if (tags.ValueKind == JsonValueKind.Array)
{
foreach (var tag in tags.EnumerateArray())
{
Console.WriteLine(tag.GetString());
}
}
}
dynamic dynamicOrder = JObject.Parse(json);
Console.WriteLine(dynamicOrder.customer.name);
// 访问数组
foreach (var contact in dynamicOrder.customer.contacts)
{
Console.WriteLine($"{contact.type}: {contact.value}");
}
处理特殊日期格式:
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() }
};
[JsonDerivedType(typeof(PhoneContact), "phone")]
[JsonDerivedType(typeof(EmailContact), "email")]
public abstract class ContactBase { /*...*/ }
public class PhoneContact : ContactBase { /*...*/ }
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());
}
}
DeserializeAsync
System.Text.Json
:性能更高,内存占用少Newtonsoft.Json
:功能更全面属性映射失败:
[JsonPropertyName("customName")]
特性日期格式异常:
options.Converters.Add(new DateTimeConverterUsingDateTimeParse());
循环引用:
options.ReferenceHandler = ReferenceHandler.Preserve;
通过合理选择工具和模式,C#可以优雅地处理各种复杂JSON结构。建议:
- 简单场景优先使用System.Text.Json
- 需要动态特性时选择Newtonsoft.Json
- 关键路径考虑使用源生成器提升性能
(注:实际字数约1500字,可根据需要删减部分章节调整到1200字左右)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。