【问题标题】:Newtonsoft Json array deserialize or is this just a listNewtonsoft Json 数组反序列化或者这只是一个列表
【发布时间】:2019-04-18 20:34:51
【问题描述】:

如果我没记错的话,https://status.cloud.google.com/incidents.jsonGoogle 正在使用 Json 数组。我正在使用 Newtonsoft.Json 并使用下面的代码反序列化 json。我是否使用正确的方法来提取 json?

using (var webClient = new WebClient())
{
    String rawJSON = webClient.DownloadString("https://status.cloud.google.com/incidents.json");
    StatusCollection statusCollection = JsonConvert.DeserializeObject<StatusCollection>(rawJSON);
    Console.WriteLine(statusCollection.Statuses.Count);
}

status.cs

namespace StatusJSONv1
{

    public class Status
    {
        string Begin { get; set; }
        string Created { get; set; }
        string End { get; set; }
        string External_desc { get; set; }
        string Modified { get; set; }
        MRUpdateContainer Most_recent_update { get; set; }
        int Number { get; set; }
        bool Public { get; set; }
        string Service_key { get; set; }
        string Service_name { get; set; }
        string Severity { get; set; }
        List<Update> Updates { get; set; }
        string Uri { get; set; }
    }


    public class MRUpdateContainer
    {
        string Created { get; set; }
        string Modified { get; set; }
        string Text { get; set; }
        string When { get; set; }
    }
    public class Update
    {
        string Created { get; set; }
        string Modified { get; set; }
        string Text { get; set; }
        string When { get; set; }
    }
}

【问题讨论】:

  • Am I using the right method to pull in the json?你试过了吗?statusCollection是什么,你在检查计数不是你,是什么?

标签: c# json json.net


【解决方案1】:

是的,您链接到的 JSON 是一个 JSON 数组。所以你需要将它反序列化成一个列表(或数组)。

List<Status> statusCollection = JsonConvert.DeserializeObject<List<Status>>(rawJSON);
Console.WriteLine(statusCollection.Count);

但是,您的代码还有一些其他问题:

  1. 你的类属性都必须是public,否则Json.Net将无法访问它们。
  2. Status 类中的 Most_recent_update 属性与 JSON 中的名称不匹配(JSON 对此属性使用连字符)。要解决此问题,您需要在类中使用 [JsonProperty] 属性,如下所示:

    [JsonProperty("most-recent-update")]
    public MRUpdateContainer Most_recent_update { get; set; }
    

    您可以在任何时候使用 [JsonProperty] 在您的类中使用与 JSON 中不同的属性名称。

小提琴:https://dotnetfiddle.net/8FtAJg

【讨论】:

  • 很高兴我能帮上忙。
猜你喜欢
  • 2021-10-13
  • 2017-10-16
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 2018-01-11
相关资源
最近更新 更多