【问题标题】:How to parse a JSON object into class using C#如何使用 C# 将 JSON 对象解析为类
【发布时间】:2021-07-03 03:02:24
【问题描述】:

我的 Json 对象

{"returnStatus":{"code":"0200","status":"SUCCESS","message":"The operation was successful.","requestTime":"20210407141112083","responseTime":"20210407141112256"},"allCities":[{"cityID":2622,"cityName":" UNKNOWN","cityCode":"AAA","area":"KHI"}

我想解析成class.How? 如何获取cityID、CityName、cityCode、area等。

我正在尝试这段代码

allCities Cities = JsonConvert.DeserializeObject<dynamic>(response);

【问题讨论】:

  • 好的,然后?您发布的代码有什么问题?
  • 我们得到这种类型的错误。解析值时遇到意外字符
  • 您发布的 json 无效(缺少 "]}" 这些关闭标签)。
  • 不要使用dynamic,除非你真的,真的必须这样做。只需创建一个代表 JSON 的类,就像 Ryan Thoma 的回答所建议的那样。

标签: c# asp.net json asp.net-mvc parsing


【解决方案1】:

您可以像 Ryan 之前所说的那样使用在线工具从您的 json 创建类。但我更喜欢使用 Visual Studio 中集成的“Paste Special”功能。

【讨论】:

    【解决方案2】:

    您可以使用Json2CSharp 创建类来反序列化您的对象。如果您愿意,可以相应地重命名它们。

    // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    public class ReturnStatus
    {
        public string code { get; set; }
        public string status { get; set; }
        public string message { get; set; }
        public string requestTime { get; set; }
        public string responseTime { get; set; }
    }
    
    public class AllCity
    {
        public int cityID { get; set; }
        public string cityName { get; set; }
        public string cityCode { get; set; }
        public string area { get; set; }
    }
    
    public class Root
    {
        public ReturnStatus returnStatus { get; set; }
        public List<AllCity> allCities { get; set; }
    }
    

    然后您可以使用 myDeserializedClass.allCities 访问城市列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 2017-03-18
      • 1970-01-01
      相关资源
      最近更新 更多