C#解析多个数组嵌套并且有其他数据类型混合的json字符串
时间: 2024-03-20 10:41:24 浏览: 191
你可以使用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]
]
}";
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 row in scores)
{
foreach (int score in row)
{
Console.Write(score + " ");
}
Console.WriteLine();
}
}
}
```
在这个示例中,我们使用Json.NET将JSON字符串解析为JObject对象。然后,我们可以使用JObject的索引器来访问对象中的属性和嵌套对象,使用JArray来访问数组和嵌套数组。
阅读全文