-1

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

1 回答 1

1

您的 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; }
}
于 2013-06-05T21:29:37.923 回答