用c#解析多个数组嵌套,和其他数据类型共有的json字符串
时间: 2024-03-20 16:41:19 浏览: 132
c#利用Newtonsoft.Json解析json(带数组)
可以使用Json.NET库来解析多个数组嵌套的JSON字符串,以及其他数据类型共有的JSON字符串。下面是一个简单的示例:
```csharp
using Newtonsoft.Json;
using System;
class Program
{
static void Main(string[] args)
{
// JSON字符串
string json = @"{
""name"": ""John Smith"",
""age"": 30,
""isMarried"": true,
""hobbies"": [""reading"", ""swimming""],
""address"": {
""street"": ""123 Main St"",
""city"": ""New York"",
""state"": ""NY"",
""zip"": ""10001""
}
}";
// 将JSON字符串反序列化为dynamic对象
dynamic data = JsonConvert.DeserializeObject(json);
// 访问对象的属性
Console.WriteLine("Name: " + data.name);
Console.WriteLine("Age: " + data.age);
Console.WriteLine("Is Married: " + data.isMarried);
// 访问数组和嵌套对象的属性
Console.WriteLine("Hobbies:");
foreach (string hobby in data.hobbies)
{
Console.WriteLine("- " + hobby);
}
Console.WriteLine("Address:");
Console.WriteLine("- Street: " + data.address.street);
Console.WriteLine("- City: " + data.address.city);
Console.WriteLine("- State: " + data.address.state);
Console.WriteLine("- Zip: " + data.address.zip);
Console.ReadLine();
}
}
```
运行结果:
```
Name: John Smith
Age: 30
Is Married: True
Hobbies:
- reading
- swimming
Address:
- Street: 123 Main St
- City: New York
- State: NY
- Zip: 10001
```
阅读全文