我有一个看起来像这样的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
为空。我完全不明白为什么?
答案 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);