2010-10-30 52 views
0

我正在寻找一个简单的示例,从一个url调用一个feed,然后循环遍历数据在C#中拉出值。.NET处理JSON供稿

我设法得到饲料数据到像这样的字符串变量。我看了看newtonsoft.Json DLL,但找不到一个简单的例子,将数据拉出来。数据并不复杂,我已将其添加到底部。

所以基本_feedData现在包含我的JSON数据我不知何故想将它转换成一个JSON对象,然后foreach它拉出的值。

 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" 
} 
] 

感谢您的帮助。 Rob

+0

这个帖子有你需要的一切:http://stackoverflow.com/questions/1212344/parse-json-in-c – Nix 2010-10-30 15:37:50

回答

0

创建一个类来存放馈送数据的一个实例。

public class FeedData 
{ 
    public string id { get; set; } 
    public string title { get; set; } 
    public string fulltext { get; set; } 
    public string url { get; set; } 
} 

然后在将json响应作为字符串反序列化到FeedData对象列表中之后。

var serializer = new DataContractJsonSerializer(typeof(List<FeedData>)); 
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(jsonResponse))) 
{ 
    var serializer = new DataContractJsonSerializer(typeof(List<FeedData>)); 
    return serializer.ReadObject(ms) as List<FeedData>; 
} 

请注意,你的返回值现在应该List<FeedData>IEnumerable<FeedData>

0

,而不是一个JSON对象,我想你需要解析JSON字符串CLR对象,对不对?

This documentation page mentioned this。

2

按照json-net项目:

对于你只从JSON获得价值感兴趣,其中的情况下,没有一个类序列化或反序列化或JSON是从你的类完全不同的,你需要手动读写你的对象,然后LINQ to JSON就是你应该使用的。 LINQ to JSON允许您在.NET中轻松读取,创建和修改JSON。

而且LINQ到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]; 
// Small