-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で遊んだところ、次の1つがうまくいきました:

[{"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 に答える