在c#中反序列化JSON

本文关键字:JSON 反序列化 | 更新日期: 2023-09-27 18:17:01

我试图在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": ""}]

在c#中反序列化JSON

你的json是正确的,如果你应该改变类定义如下,那么这将工作

(顺便说一句:你可能会发现这个网站很有用)

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; }
}