我有一个看起来像这样的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
为null。我完全不明白为什么?
在您的DailyNewsList
类中,transactions
属性名称与JSON中的内容不匹配,即dailyNews
。您可以通过使用[JsonProperty]
属性来装饰transactions
属性来解决此问题,就像您在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