是的,C# 中的 JArray
(通常與 Newtonsoft.Json 庫一起使用)可以處理復雜的數據。它可以輕松地序列化和反序列化 JSON 數據,包括嵌套的對象和數組。這使得 JArray
成為處理來自 API、文件或其他數據源的復雜 JSON 數據的理想選擇。
以下是一個簡單的示例,說明如何使用 JArray
處理復雜數據:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string json = @"{
""name"": ""John"",
""age"": 30,
""isStudent"": false,
""courses"": [
{
""name"": ""Math"",
""grade"": 90
},
{
""name"": ""English"",
""grade"": 85
}
],
""address"": {
""street"": ""123 Main St"",
""city"": ""New York"",
""state"": ""NY"",
""zipCode"": ""10001""
}
}";
// Deserialize JSON to JObject
JObject jsonObject = JsonConvert.DeserializeObject<JObject>(json);
// Access complex data
string name = jsonObject["name"].ToString();
int age = jsonObject["age"].ToObject<int>();
bool isStudent = jsonObject["isStudent"].ToObject<bool>();
List<JObject> courses = jsonObject["courses"].ToObject<List<JObject>>();
JObject address = jsonObject["address"].ToObject<JObject>();
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Is Student: {isStudent}");
Console.WriteLine("Courses:");
foreach (var course in courses)
{
string courseName = course["name"].ToString();
int courseGrade = course["grade"].ToObject<int>();
Console.WriteLine($" {courseName}: {courseGrade}");
}
Console.WriteLine($"Address:");
Console.WriteLine($" Street: {address["street"]}");
Console.WriteLine($" City: {address["city"]}");
Console.WriteLine($" State: {address["state"]}");
Console.WriteLine($" Zip Code: {address["zipCode"]}");
}
}
在這個示例中,我們首先將 JSON 字符串反序列化為 JObject
。然后,我們可以輕松地訪問和處理嵌套的對象和數組。