我有jsonstring:
{
"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 :(得分: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;
}