json.net使用linq反序列化

时间:2014-04-30 10:12:29

标签: c# linq json.net

我有这个JSON字符串:

{
    "12":  ["game 1", 2428.8],
    "425": ["game 2",113.91],
    "40":  ["one more game name",6341.46],
    "30":  ["game name x",7535.57],
    "total": 8000.33
}

我希望使用json.net将其解析为一个对象:

public class Game
{
    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Amount { get; set; }
}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用Json.Net解析您的JSON字符串,如下所示:

JObject jo = JObject.Parse(json);
List<Game> games = new List<Game>();
foreach (JProperty prop in jo.Properties())
{
    if (prop.Value.Type == JTokenType.Array)
    {
        games.Add(new Game
        {
            ID = Convert.ToInt32(prop.Name),
            Name = (string)prop.Value[0],
            Amount = (int)prop.Value[1]
        });
    }
}