使用JavaScriptSerializer反序列化JSON

时间:2015-07-29 17:26:15

标签: c# json deserialization

我遇到了JSON反序列化问题。我有这样的JSON字符串:

{
    "event": [
        [
            {
                "Id": 456895,
                "Name": "Chelsea - Arsenal",
                "BetOffers": [
                    {
                        "BetType": "Game",
                        "Picks": [
                            {
                                "Pick": "1",
                                "Odds": 1.15
                            },
                            {
                                "Pick": "x",
                                "Odds": 1.46
                            },
                            {
                                "Pick": "2",
                                "Odds": 1.15
                            }
                        ]
                    }
                ]
            }
        ],
        [
            {
                "Id": 456879,
                "Name": "Liverpool - Manchester United",
                "BetOffers": [
                    {
                        "BetType": "Game",
                        "Picks": [
                            {
                                "Pick": "1",
                                "Odds": 1.20
                            },
                            {
                                "Pick": "x",
                                "Odds": 1.42
                            },
                            {
                                "Pick": "2",
                                "Odds": 1.85
                            }
                        ]
                    }
                ]
            }
        ]
    ]
}

我根据这个创建了类:

public class Event
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<BetOffer> BetOffers { get; set; }
}

public class BetOffer
{
    public string BetType { get; set; }
    public List<BetPick> Picks { get; set; }
}

public class BetPick
{
    public string Pick { get; set; }
    public double Odds { get; set; }
}

当我反序列化该JSON字符串时,我最终得到了空列表。这就是我正在进行反序列化的方法:

var jsonString = File.ReadAllText(filePath);
var result = new JavaScriptSerializer().Deserialize<List<Event>>(jsonString);

我的结果中的值是空列表(Count = 0)。我哪里做错了?有没有更好的方法从这个JSON创建一个对象?

1 个答案:

答案 0 :(得分:3)

你的模型应该有点不同。

public class PickItem
{
    public string Pick { get; set; }
    public double Odds { get; set; }
}

public class BetOffer
{
    public string BetType { get; set; }
    public List<PickItem> Picks { get; set; }
}

public class BetPick
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<BetOffer> BetOffers { get; set; }
}

public class MyRootObject
{
    public List<List<BetPick>> @event { get; set; }
}
var root = new JavaScriptSerializer().Deserialize<MyRootObject>(jsonString);