为什么我从JSON反序列化返回了NULL?

时间:2019-05-09 20:03:03

标签: json c#-4.0 json.net

我有一个看起来像这样的JSON文件:

{
  "dailyNews": [
    {
      "string": "D5FCF84D-B1A2-4172-9A93-E88342AA9E3C",
      "updateDate": "2019-04-24T00:00:00Z",
      "titleText": "something",
      "mainText": "sometihng ",
      "redirectionUrl": " "
    },
    {
      "string": "D5FCF84D-B1A2-4172-9A93-E88342AA9E3C",
      "updateDate": "2019-04-24T00:00:00Z",
      "titleText": "something1",
      "mainText": "sometihng2",
      "redirectionUrl": " "
    },
    {
      "string": "D5FCF84D-B1A2-4172-9A93-E88342AA9E3C",
      "updateDate": "2019-04-24T00:00:00Z",
      "titleText": "something3",
      "mainText": "sometihng4",
      "redirectionUrl": " "
    }
  ]
}

我有一个使用JSON2CSharp生成的C#类。此类看起来像这样:

public partial class TodaysNews
{
    [JsonProperty("string")]
    public string String { get; set; }

    [JsonProperty("updateDate")]
    public DateTimeOffset UpdateDate { get; set; }

    [JsonProperty("titleText")]
    public string TitleText { get; set; }

    [JsonProperty("ImageSrc")]
    public Uri ImageSrc { get; set; }

    [JsonProperty("mainText")]
    public string MainText { get; set; }

    [JsonProperty("redirectionUrl")]
    public Uri RedirectionUrl { get; set; }
}

public class DailyNewsList
{
    public List<TodaysNews> transactions { get; set; }
   // public int count { get; set; }
}

这是将反序列化的代码:

public static DailyNewsList FromJson(string json) => 
    JsonConvert.DeserializeObject<TodaysNews>(json, S3Reader.Converter.Settings);

一切正常;对象TodaysNews已初始化,但是列表对象transactions为空。我完全不明白为什么?

1 个答案:

答案 0 :(得分:1)

在您的DailyNewsList类中,transactions属性名称与JSON中的dailyNews不匹配。您可以通过像在transactions类中一样用[JsonProperty]属性修饰TodaysNews属性来解决此问题:

public class DailyNewsList
{
    [JsonProperty("dailyNews")]
    public List<TodaysNews> transactions { get; set; }
}

此外,在您的FromJson方法中,您应该反序列化为DailyNewsList而不是TodaysNews

public static DailyNewsList FromJson(string json) => 
    JsonConvert.DeserializeObject<DailyNewsList>(json, S3Reader.Converter.Settings);

提琴:https://dotnetfiddle.net/5pihJE