Deserializing JSON and converting them to C# objects
I have a silverlight web application. From this app I am making a call to JSP pages using WebClient
class. Now JSP returns a response in JSON format
{
"results":[{"Value":"1","Name":"Advertising"},
{"Value":"2","Name":"Automotive Expenses"},{"Value":"3","Name":"Business Miscellaneous"}]
}
The above response is assigned to my Stream object.
I have a c# class CategoryType
public class CategoryType
{
public string Value{get;set开发者_StackOverflow;}
public string Name{get;set;}
}
My aim is to convert the reponses in to Collection<CategoryType>
and use it in my C# Code
As of now I am trying to use DataContractJSONSerialiser
. But not sure if there is an easy and efficent way to do this. Any help would be appreciated
Its JSON and to convert it to object you need to deserialize it to object. many tools are available from Microsoft and Third party .
And you seem to be going the right way.
I have used JavascriptSerializer
. See its use here http://shekhar-pro.blogspot.com/2011/01/serializing-and-deserializing-data-from.html
or use a great library JSON.Net used extensively even before Microsoft released those libraries.
Update
As you mentioned in your comments you want to convert it to Collection you could do it like this:
create array class to represent array of items.
public class CategoryTypeColl
{
public CategoryType[] results {get;set;}
}
and in your code
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.
精彩评论