如何将此JSON解析为C#对象?

时间:2013-12-09 21:51:31

标签: c# json json.net

我有一个JSON流,我想将其解析为C#对象。这个流不是我可以改变的东西,所以我必须处理它,但它似乎不对吗?

无论如何谁知道如何在例如帮助下解析这个问题。 JSON.NET?

[
{
    "items": {
        "4": {
            "IdNummer": "4",
            "Title": "Bewaak je hart deel 3",
            "Server": "cdn11.streampartner.nl",
            "PublishPoint": "plompd",
            "Filename": "Bewaak je hart deel 3.mp3",
            "activated": "1",
            "Date": "Dec 21:12",
            "Filesize": "28950111",
            "Thumbnail": "",
            "Comments": "",
            "UserToken": "plom04a18847262fe15",
            "ItemTokenNumber": "0661ce1e4fe256d1",
            "Category": "",
            "StartDate": "0000-00-00",
            "EndDate": "0000-00-00"
        },
        "5": {
            "IdNummer": "5",
            "Title": "Bewaak je hart deel 2",
            "Server": "cdn11.streampartner.nl",
            "PublishPoint": "plompd",
            "Filename": "Bewaak je hart deel 2.mp3",
            "activated": "1",
            "Date": "Dec 22:37",
            "Filesize": "41461227",
            "Thumbnail": "",
            "Comments": "",
            "UserToken": "plom04a18847262fe15",
            "ItemTokenNumber": "6b8eddbf612653e9",
            "Category": "",
            "StartDate": "0000-00-00",
            "EndDate": "0000-00-00"
        }
    }
}

1 个答案:

答案 0 :(得分:2)

由于您的json包含数字属性名称,如"1",不能在c#中用作变量名,因此您可以使用Dictionary<string,SomeObject>技巧。所以使用Json.Net,

var obj = JsonConvert.DeserializeObject<List<ItemContainer>>(json);

public class ItemContainer
{
    public Dictionary<string,Item> Items { get; set; }
}
public class Item
{
    public string IdNummer { get; set; }
    public string Title { get; set; }
    public string Server { get; set; }
    public string PublishPoint { get; set; }
    public string Filename { get; set; }
    public string activated { get; set; }
    public string Date { get; set; }
    public string Filesize { get; set; }
    public string Thumbnail { get; set; }
    public string Comments { get; set; }
    public string UserToken { get; set; }
    public string ItemTokenNumber { get; set; }
    public string Category { get; set; }
    public string StartDate { get; set; }
    public string EndDate { get; set; }
}