. Net2.0
Markerarr = "[{Name: 'apple', price: 5.5}, {Name: 'orange', price: 2.5}, {Name: 'persimmon ', price: 16}] ";
Oldlst = (list <mappointdata>) javascriptconvert. deserializeobject (markerarr, typeof (list <mappointdata>); // All page data
. Net3.5
C # deserializing a json string into a list object class set
Using system. IO;
Using system. Web. Script. serialization;
Using system. runtime. serialization. JSON;
Public static list <t> jsonstringtolist <t> (this string jsonstr)
{
Javascriptserializer serializer = new javascriptserializer ();
List <t> objs = serializer. deserialize <list <t> (jsonstr );
Return objs;
}
Public static t deserialize <t> (string JSON)
{
T OBJ = activator. createinstance <t> ();
Using (memorystream MS = new memorystream (encoding. utf8.getbytes (JSON )))
{
Datacontractjsonserializer serializer = new datacontractjsonserializer (obj. GetType ());
Return (t) serializer. readobject (MS );
}
}
Okay, let's test it.
String jsonstr = "[{Name: 'apple', price: 5.5}, {Name: 'orange', price: 2.5}, {Name: 'persimmon ', price: 16}] ";
List <product> Products = new list <product> ();
Products = jsonstringtolist <product> (jsonstr );
// Response. Write (products. Count ());
Foreach (VAR item in products)
{
Response. Write (item. Name + ":" + item. Price + "<br/> ");
}
Public class product
{
Public string name {Get; set ;}
Public double price {Get; set ;}
}
Result:
Apples: 5.5
Oranges: 2.5
Persimmon: 16
C # serialize an object into a JSON string
Using system. Web. Script. serialization;
Public void processrequest (httpcontext context)
{
Context. response. contenttype = "text/plain ";
List <product> Products = new list <product> (){
New product () {name = "apple", price = 5.5 },
New product () {name = "orange", price = 2.5 },
New product () {name = "dried persimmon", price = 16.00}
};
Productlist = new productlist ();
Productlist. getproducts = products;
Context. response. Write (New javascriptserializer (). serialize (productlist ));
}
Public bool isreusable
{
Get
{
Return false;
}
}
Public class product
{
Public string name {Get; set ;}
Public double price {Get; set ;}
}
Public class productlist
{
Public list <product> getproducts {Get; set ;}
}
The JSON result is as follows:
{"Getproducts": [{"name": "apple", "price": 5.5 },{ "name": "orange", "price": 2.5 }, {"name": "persimmon", "price": 16}]}