首页 > 解决方案 > Json.net 反序列化类数组的数组

问题描述

我通过 URL 接收 JSON 数据,如下所示:

 {
       "destination_addresses" : [ "example address" ],
       "origin_addresses" : [ "example address" ],
       "rows" : [
          {
             "elements" : [
                {
                   "distance" : {
                      "text" : "220 ft",
                      "value" : 67
                   },
                   "duration" : {
                      "text" : "1 min",
                      "value" : 12
                   },
                   "status" : "OK"
                }
             ]
          }
       ],
       "status" : "OK"
    }

我正在尝试反序列化为以下类:

public class APIDistance
        {
    
        public class Rootobject
        {
            public string[] destination_addresses { get; set; }
            public string[] origin_addresses { get; set; }
            public Row[] rows { get; set; }
            public string status { get; set; }
        }

        public class Row
        {
            public Element[] elements { get; set; }
        }

        public class Element
        {
            public Distance distance { get; set; }
            public Duration duration { get; set; }
            public string status { get; set; }
        }

        public class Distance
        {
            public string text { get; set; }
            public int value { get; set; }
        }

        public class Duration
        {
            public string text { get; set; }
            public int value { get; set; }
        }

   }

我的问题是我不知道如何向班级分配和/或读取数据。我遵循的示例建议您应该使用 JsonConvert.DeserializeObject 然后使用该对象来获取所需的属性,但是,我似乎无法找到任何属性: 在此处输入图像描述

被告知要使用 newtonsoft,因为这很“简单”,但没有找到我尝试使用的 Json 结构的任何示例。

Json 新手,非常感谢任何帮助。提前致谢。

标签: c#jsonjson.net

解决方案


删除 public class APIDistance { 这里只是用作嵌套类的父级。而是像这样反序列化 Rootobject JsonConvert.DeserializeObject(json) – Charlieface 18 分钟前


推荐阅读