2015-05-19 88 views
-1

我有jsonstring:如何從json獲得一些價值而不是roor?

{ 
"kind": "youtube#videoListResponse", 
"etag": "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/o3L50v5R2WwnOWFaoCXQIOzRQt8\"", 
"pageInfo": { 
    "totalResults": 1, 
    "resultsPerPage": 1 
}, 
"items": [ 
    { 
    "kind": "youtube#video", 
    "etag": "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/emOU-eLbb23xAEX_1JcXPAXYJUY\"", 
    "id": "7eCPp1WLpyA", 
    "contentDetails": { 
    "duration": "PT7M10S", 
    "dimension": "2d", 
    "definition": "hd", 
    "caption": "false", 
    "licensedContent": true 
    }, 
    "statistics": { 
    "viewCount": "1603", 
    "likeCount": "454", 
    "dislikeCount": "6", 
    "favoriteCount": "0", 
    "commentCount": "107" 
    } 
    } 
] 
} 

我想時間的值是 「PT7M10S」

我正在編碼:

var obj = JObject.Parse(jsonString); 
var url = (string)obj["contentDetails"]["duration"]; 
return url; 

,但我得到的錯誤:對象引用未設置爲一個對象的實例 請大家幫忙!謝謝。

+0

檢查您的JSON - 頂級沒有「contentDetails」... –

回答

2

您正在尋找的財產是在items陣列。所以,你需要做到以下幾點:

var obj = JObject.Parse(json); 
var url = obj["items"][0]["contentDetails"]["duration"]; 

小提琴: https://dotnetfiddle.net/iSNzAe

編輯:這樣做的更好的辦法是使用一個類(請參閱更新小提琴)

public static void Main() 
{  
    var json = 
    @"{ 
    ""kind"": ""youtube#videoListResponse"", 
    ""etag"": ""\""NO6QTeg0-3ShswIeqLchQ_mzWJs/o3L50v5R2WwnOWFaoCXQIOzRQt8\"""", 
    ""pageInfo"": { 
     ""totalResults"": 1, 
     ""resultsPerPage"": 1 
    }, 
    ""items"": [ 
     { 
     ""kind"": ""youtube#video"", 
     ""etag"": ""\""NO6QTeg0-3ShswIeqLchQ_mzWJs/emOU-eLbb23xAEX_1JcXPAXYJUY\"""", 
     ""id"": ""7eCPp1WLpyA"", 
     ""contentDetails"": { 
     ""duration"": ""PT7M10S"", 
     ""dimension"": ""2d"", 
     ""definition"": ""hd"", 
     ""caption"": ""false"", 
     ""licensedContent"": true 
     }, 
     ""statistics"": { 
     ""viewCount"": ""1603"", 
     ""likeCount"": ""454"", 
     ""dislikeCount"": ""6"", 
     ""favoriteCount"": ""0"", 
     ""commentCount"": ""107"" 
     } 
     } 
    ] 
    }"; 

    var obj = JsonConvert.DeserializeObject<Response>(json); 
    var duration = obj.items.First().contentDetails.duration; 

    Console.WriteLine(duration); 

} 

public class Response 
{ 
    public IEnumerable<ResponseItem> items; 
} 

public class ResponseItem 
{ 
    public ContentDetails contentDetails; 
} 

public class ContentDetails 
{ 
    public string duration; 
} 
+0

工作好友!非常感謝<3 –