使用C#和Visual Studio 2010(Windows窗体项目),InstaSharp和Newtonsoft.Json库。
当我请求特定主题标签时,我想从端点 Instagram API返回给我的JSON字符串中获取图片网址。
到目前为止我可以检索JSON字符串。
我正在尝试使用 Newtonsoft.Json 来使用示例反序列化对象,但我可能不理解对象的JSON字符串表示。
以下是我从其文档中的api调用response
获得的简化示例tags/tag-name/media/recent
。 source here
{
"data": [{
"type": "image",
"filter": "Earlybird",
"tags": ["snow"],
"comments": {
}
"caption": {
},
"likes": {
},
"created_time": "1296703536",
"images": {
"low_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_7.jpg",
"width": 612,
"height": 612
}
},
"id": "22699663",
"location": null
},
...
]
}
我想具体了解standard_resolution
部分中的images
。
这是我目前拥有的相关代码。
//Create the Client Configuration object using Instasharp
var config = new InstaSharp.Endpoints.Tags.Unauthenticated(config);
//Get the recent pictures of a particular hashtag (tagName)
var pictures = config.Recent(tagName);
//Deserialize the object to get the "images" part
var pictureResultObject = JsonConvert.DeserializeObject<dynamic>(pictureResult.Json);
consoleTextBox.Text = pictureResult.Json;
var imageUrl = pictureResultObject.Data.Images;
Console.WriteLine(imageUrl);
我收到错误:Additional information: Cannot perform runtime binding on a null reference
因此imageUrl
在调试时确实为空,因此表明我没有以正确的方式访问它。
任何人都可以向我解释如何使用 Newtonsoft.Json 访问此JSON字符串的不同部分?
答案 0 :(得分:5)
使用 Newtonsoft.Json
dynamic dyn = JsonConvert.DeserializeObject(json);
foreach (var data in dyn.data)
{
Console.WriteLine("{0} - {1}",
data.filter,
data.images.standard_resolution.url);
}
答案 1 :(得分:1)
我为.net编写了一个插件,它负责反序列化json字符串并返回数据表。它仍在开发中,但看看它是否有帮助。 Instagram.NET on Github