2016-10-04 130 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