2011-02-02 98 views
1

我有一個Silverlight Web應用程序。在這個應用程序中,我使用WebClient類來調用JSP頁面。現在JSP以JSON格式返回響應反序列化JSON並將它們轉換爲C#對象

{ 
"results":[{"Value":"1","Name":"Advertising"}, 
{"Value":"2","Name":"Automotive Expenses"},{"Value":"3","Name":"Business Miscellaneous"}] 
} 

上述響應被分配給我的Stream對象。

我有一個C#類CategoryType

public class CategoryType 
{ 
public string Value{get;set;} 
public string Name{get;set;} 
} 

我的目標是在反應變量轉換到Collection<CategoryType>和截至目前,我試圖用DataContractJSONSerialiser使用它在我的C#代碼

。但不知道是否有一個簡單而有效的方法來做到這一點。任何幫助,將不勝感激

+0

是否Web服務支持JSON以外的任何其他輸出?有沒有wsdl? – Marco 2011-02-02 07:20:26

回答

2

其JSON和將其轉換爲對象,你需要反序列化它的對象。許多工具可從Microsoft和第三方獲得。

而你似乎正在走正確的道路。

我已經使用JavascriptSerializer。在這裏看到它的用處http://shekhar-pro.blogspot.com/2011/01/serializing-and-deserializing-data-from.html

或者使用一個偉大的庫JSON.Net甚至在微軟發佈這些庫之前就已經廣泛使用了。

更新

正如你在評論中提到要將其轉換爲Collection,你可以做這樣的:

創建數組類來表示項目的數組。

public class CategoryTypeColl 
{ 
    public CategoryType[] results {get;set;} 
} 

,並在你的代碼

Collection<CategoryType> ctcoll = new Collection<CategoryType>(); 
JavaScriptSerializer jsr = new JavaScriptSerializer(); 
CategoryTpeColl ctl = jsr.Deserialize<CategoryTypeColl>(/*your JSON String*/); 
List<CategoryType> collection = (from item in ctl.results 
           select item).ToList(); 
//If you have implemented Icollection then you can use yourcollection and Add items in a foreach loop.