2016-10-04 98 views
0

我需要使用C#解析JSON数据,它是数组的集合。如何使用C#解析JSON数组#

ItemRelations: [ 
    { 
     rel: "System.Links.H-Forward", 
     source: {id: 123456,url: "https://somename.domain.com/DefaultCollection/_apis/wit/Items/123456"}, 
     target: {id: 231856,url: "https://somename.domain.com/DefaultCollection/_apis/wit/Items/231856"} 
    } 
] 

我可以分析简单的JSON字符串,但是当涉及场景像上面我应该如何着手?

+2

参考http://stackoverflow.com/questions/15726197/parsing-a-json-array-using-json-net link.it可能帮助ü –

+0

搜索Newtonsoft .Json并阅读一些文档。它非常强大,你可能甚至不需要做太多的事情。另外visual studio有一个功能Edit-> Paste Special - >将JSON粘贴为Classes。 – Mafii

+2

看看http://www.newtonsoft.com/json。这可能有助于 – GeekBoy

回答

0

您可以使用Json2csharp为您的json生成类。然后使用Json.Net从的NuGet:

void Main() 
{ 
    var json = @"{ItemRelations: [ 
    { 
     rel: ""System.Links.H-Forward"", 
     source: {id: 123456,url: ""https://somename.domain.com/DefaultCollection/_apis/wit/Items/123456""}, 
     target: {id: 231856,url: ""https://somename.domain.com/DefaultCollection/_apis/wit/Items/231856""} 
    } 
]}"; 

    var parsed = JsonConvert.DeserializeObject<RootObject>(json); 

    //Linqpad 
    //parsed.Dump(); 
} 

public class Source 
{ 
    public int id { get; set; } 
    public string url { get; set; } 
} 

public class Target 
{ 
    public int id { get; set; } 
    public string url { get; set; } 
} 

public class ItemRelation 
{ 
    public string rel { get; set; } 
    public Source source { get; set; } 
    public Target target { get; set; } 
} 

public class RootObject 
{ 
    public List<ItemRelation> ItemRelations { get; set; } 
} 
+0

谢谢你们! – Abhi