在C#中,可以使用LitJSON庫(kù)來(lái)解析復(fù)雜的JSON結(jié)構(gòu)。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何使用LitJSON解析一個(gè)包含嵌套結(jié)構(gòu)和數(shù)組的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);
}
}
在這個(gè)示例中,首先將JSON字符串轉(zhuǎn)換為JsonData對(duì)象,然后通過索引訪問對(duì)象的屬性和數(shù)組元素,從而獲取JSON中的數(shù)據(jù)。通過遞歸訪問嵌套結(jié)構(gòu)和數(shù)組,可以方便地解析復(fù)雜的JSON數(shù)據(jù)。