假设我们有以下的 JSON 数据:

{
  "name": "John",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY"
  }
}

我们可以使用 C# 中的 Newtonsoft.Json 库来解析它,代码如下:

using Newtonsoft.Json;
using System;

class Program
{
    static void Main(string[] args)
    {
        string json = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\",\"state\":\"NY\"}}";
        
        dynamic data = JsonConvert.DeserializeObject(json);
        
        Console.WriteLine("Name: " + data.name);
        Console.WriteLine("Age: " + data.age);
        Console.WriteLine("Street: " + data.address.street);
        Console.WriteLine("City: " + data.address.city);
        Console.WriteLine("State: " + data.address.state);
    }
}

输出结果为:

Name: John
Age: 30
Street: 123 Main St
City: New York
State: NY

我们首先将 JSON 字符串转换为 dynamic 类型的对象,然后通过对象的属性来访问 JSON 中的值。在这个例子中,我们可以访问 nameage 属性的值,以及 address 属性下的 streetcitystate 属性的值。


原文地址: https://www.cveoy.top/t/topic/6U0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录