我正在寻找一个简单的示例,该示例从url调用提要,然后循环遍历数据,提取C#中的值。
我设法将提要数据放入一个字符串变量中,如下所示。我查看了newtonsoft.Json动态链接库,但找不到提取数据的简单示例。数据并不复杂,我已将其添加到底部。
所以基本上_feedData现在包含了我的JSON数据,我喜欢把它转换成一个JSON对象,然后把它的值提取出来。
static void Main(string[] args)
{
string _feedData = GetJSONFeed();
}
public static string GetJSONFeed()
{
string formattedUri = "http://www.myJsonFeed.com/blah.json";
HttpWebRequest webRequest = GetWebRequest(formattedUri);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
}
return jsonResponse;
}
private static HttpWebRequest GetWebRequest(string formattedUri)
{
// Create the request’s URI.
Uri serviceUri = new Uri(formattedUri, UriKind.Absolute);
// Return the HttpWebRequest.
return (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
}我的JSON数据是这样的:
[
{
"id": "9448",
"title": "title title title",
"fulltext": "main body text",
"url": "http://www.flikr.co.uk?id=23432"
},
{
"id": "9448",
"title": "title title title",
"fulltext": "main body text",
"url": "http://www.flikr.co.uk?id=23432"
}
]谢谢你的帮助。抢夺
发布于 2010-10-31 00:01:35
遵循json-net项目:
如果您只对从JSON获取值感兴趣,没有要序列化或反序列化的类,或者JSON与您的类完全不同,而您需要手动读取和写入对象,则应该使用LINQ to
。LINQ to JSON允许您轻松地在.NET中读取、创建和修改JSON。
以及LINQ to JSON示例:
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large"
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Smallhttps://stackoverflow.com/questions/4059342
复制相似问题