用C#解析有三个数组嵌套的也有其他数据类型的json字符串
时间: 2024-03-20 20:41:26 浏览: 145
你可以使用Json.NET库来解析这样的JSON字符串。下面是一个示例代码:
```csharp
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
class Program
{
static void Main(string[] args)
{
string json = @"
{
""name"": ""John Smith"",
""age"": 30,
""isMarried"": true,
""hobbies"": [""reading"", ""swimming""],
""address"": {
""street"": ""123 Main St"",
""city"": ""New York"",
""state"": ""NY"",
""zip"": ""10001""
},
""scores"": [
[
[80, 90, 85],
[70, 75, 80]
],
[
[90, 85, 95],
[80, 85, 90]
]
]
}";
JObject obj = JsonConvert.DeserializeObject<JObject>(json);
string name = obj["name"].ToString();
int age = (int)obj["age"];
bool isMarried = (bool)obj["isMarried"];
JArray hobbies = (JArray)obj["hobbies"];
foreach (string hobby in hobbies)
{
Console.WriteLine(hobby);
}
JObject address = (JObject)obj["address"];
string street = address["street"].ToString();
string city = address["city"].ToString();
string state = address["state"].ToString();
string zip = address["zip"].ToString();
JArray scores = (JArray)obj["scores"];
foreach (JArray arr1 in scores)
{
foreach (JArray arr2 in arr1)
{
foreach (int score in arr2)
{
Console.Write(score + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}
}
```
在这个示例中,我们使用Json.NET将JSON字符串解析为JObject对象。然后,我们可以使用JObject的索引器来访问对象中的属性和嵌套对象,使用JArray来访问数组和嵌套数组。在这个例子中,我们有一个三级嵌套的数组,我们需要使用多个foreach循环来访问数组中的每个元素。
阅读全文