2016-10-28 45 views
0

所以我打電話LinkedIn API來獲取配置文件數據並檢索JSON。從嵌套的JSON值中檢索信息

{ 
    "firstName": "Cristian Viorel", 
    "headline": ".NET Developer", 
    "location": { 
    "country": {"code": "dk"}, 
    "name": "Northern Region, Denmark" 
    }, 
    "pictureUrls": { 
    "_total": 1, 
    "values": ["https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z..."] 
    } 
} 

我可以使用student.firstname,student.headline。我如何獲取位置的名稱或pictureUrl的值? 類似於student.location.name或student.pictureUrls.values?

+0

你試過你的建議? –

回答

3

Json.Net很容易。首先要定義你的模型:

public class Country 
{ 
    public string code { get; set; } 
} 

public class Location 
{ 
    public Country country { get; set; } 
    public string name { get; set; } 
} 

public class PictureUrls 
{ 
    public int _total { get; set; } 
    public List<string> values { get; set; } 
} 

public class JsonResult 
{ 
    public string firstName { get; set; } 
    public string headline { get; set; } 
    public Location location { get; set; } 
    public PictureUrls pictureUrls { get; set; } 
} 

然後你只需解析您的JSON數據:

string json = @"{ 
     'firstName': 'Cristian Viorel', 
     'headline': '.NET Developer', 
     'location': { 
     'country': {'code': 'dk'}, 
     'name': 'Northern Region, Denmark' 
     }, 
     'pictureUrls': { 
     '_total': 1, 
     'values': ['https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z...'] 
     } 
    }"; 

JsonResult result = JsonConvert.DeserializeObject<JsonResult>(json); 

Console.WriteLine(result.location.name); 

foreach (var pictureUrl in result.pictureUrls.values) 
    Console.WriteLine(pictureUrl); 
+0

它的工作原理!非常感謝亞歷克斯! – crystyxn

0

對於名稱是的,但對於圖片,你需要一個for循環,或者如果你只是想要第一個項目student.pictureUrls.values [0](值似乎是一個數組)。