我正在尝试在C#中反序列化JSON但是我得到NullReferenceException并且我不知道为什么。
这是我要解析的JSON:
{"Entries": {"Entry": {"day": "28","month": "10","year": "1955","type": "birthday","title": "Bill Gates was born!","picture": "","video": ""}}}
我正在使用此代码
public class Entry
{
public string day { get; set; }
public string month { get; set; }
public string year { get; set; }
public string type { get; set; }
public string title { get; set; }
public string picture { get; set; }
public string video { get; set; }
}
public class Entries
{
public List<Entry> entry { get; set; }
}
private void buttonSearch_Click(object sender, EventArgs e)
{
string json = new StreamReader("events.json").ReadToEnd();
var entries = JsonConvert.DeserializeObject<Entries>(json);
MessageBox.Show(entries.entry[0].day); // NullReferenceException
}
为什么我会收到此错误以及如何解决?
当我将JSON更改为
时{"Entries": ["Entry": {"day": "28","month": "10","year": "1955","type": "birthday","title": "Bill Gates was born!","picture": "","video": ""}]}
我得到After parsing a value an unexpected character was encountered: :. Path 'Entries[0]', line 1, position 20.
修改
我和JSON一起玩,而另一个人对我有用:
[{"day": "28","month": "10","year": "1955","type": "birthday","title": "Bill Gates was born!","picture": "","video": ""}]
答案 0 :(得分:1)
你的json是正确的,如果你应该按如下方式更改类定义,那么这将有效
(顺便说一句:你可能会发现this site很有用)
var entries = JsonConvert.DeserializeObject<Root>(json);
public class Entry
{
public string day { get; set; }
public string month { get; set; }
public string year { get; set; }
public string type { get; set; }
public string title { get; set; }
public string picture { get; set; }
public string video { get; set; }
}
public class Entries
{
public Entry Entry { get; set; }
}
public class Root
{
public Entries Entries { get; set; }
}