2010-10-30 49 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