反序列化JSON并将它们转换为C#对象

问题描述:

我有一个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

其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.