csharp 解析嵌套json 代码示例
时间: 2023-06-04 12:02:54 浏览: 156
JSON 解析 示例代码
以下是一种用 C# 解析嵌套 JSON 的示例代码:
```csharp
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string json = @"
{
""name"": ""John Doe"",
""age"": 30,
""address"": {
""street"": ""123 Main St"",
""city"": ""New York"",
""state"": ""NY""
},
""phoneNumbers"": [
""555-1234"",
""555-5678""
]
}";
var obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
foreach (var pair in obj)
{
Console.Write("{0}: ", pair.Key);
if (pair.Value is Dictionary<string, object>)
{
// Handle nested objects
var nestedObj = pair.Value as Dictionary<string, object>;
foreach (var nestedPair in nestedObj)
{
Console.Write("{0}.{1}: {2} ", pair.Key, nestedPair.Key, nestedPair.Value);
}
}
else if (pair.Value is List<object>)
{
// Handle arrays
var array = pair.Value as List<object>;
var index = 0;
foreach (var item in array)
{
Console.Write("{0}[{1}]: {2} ", pair.Key, index++, item);
}
}
else
{
Console.Write("{0} ", pair.Value);
}
Console.WriteLine();
}
}
}
```
其中,使用了 Newtonsoft.Json 库来解析 JSON,将 JSON 字符串解析为一个 `Dictionary<string, object>` 对象。然后,使用了一些简单的逻辑来处理嵌套的 JSON 对象和数组。这段代码可以输出如下结果:
```
name: John Doe
age: 30
address.street: 123 Main St
address.city: New York
address.state: NY
phoneNumbers[0]: 555-1234
phoneNumbers[1]: 555-5678
```
阅读全文