在C#中,可以使用LitJSON庫來解析復雜的JSON結構。以下是一個簡單的示例代碼,演示如何使用LitJSON解析一個包含嵌套結構和數組的JSON:
using LitJson;
using System;
class Program
{
static void Main()
{
string json = @"
{
""name"": ""John Smith"",
""age"": 30,
""isMarried"": true,
""children"": [
{
""name"": ""Alice"",
""age"": 5
},
{
""name"": ""Bob"",
""age"": 3
}
],
""address"": {
""street"": ""123 Main St"",
""city"": ""New York"",
""zipCode"": ""10001""
}
}";
JsonData data = JsonMapper.ToObject(json);
string name = (string)data["name"];
int age = (int)data["age"];
bool isMarried = (bool)data["isMarried"];
JsonData children = data["children"];
foreach (JsonData child in children)
{
string childName = (string)child["name"];
int childAge = (int)child["age"];
Console.WriteLine("Child: {0} ({1} years old)", childName, childAge);
}
JsonData address = data["address"];
string street = (string)address["street"];
string city = (string)address["city"];
string zipCode = (string)address["zipCode"];
Console.WriteLine("Name: {0}", name);
Console.WriteLine("Age: {0}", age);
Console.WriteLine("Married: {0}", isMarried);
Console.WriteLine("Address: {0}, {1}, {2}", street, city, zipCode);
}
}
在這個示例中,首先將JSON字符串轉換為JsonData對象,然后通過索引訪問對象的屬性和數組元素,從而獲取JSON中的數據。通過遞歸訪問嵌套結構和數組,可以方便地解析復雜的JSON數據。