- Public string getjsonstring ()
- {
- 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 productlist = new ProductList ();
- ProductList. GetProducts = Products;
- return new JavaScriptSerializer (). Serialize (productlist));
- }
- Public class Product
- {
- public string Name { get; set;}
- public Double price { get; set;}
- }
- Public class ProductList
- {
- Public list<product> getproducts { get; set;}
- }
The main thing here is to use JavaScriptSerializer to implement serialization, so that we can convert the object into a JSON-formatted string, resulting in the following results:
- {"getproducts": [{"name":"apple","price": 5.5},{"name":"Orange","price": 2.5},{"name": "Persimmon","price": 16}]}
How do I convert a JSON string into an object?
In actual development, it is often possible to encounter using JS to pass a JSON-formatted string into the background, if you can automatically convert the string to the desired object, it is more convenient to traverse or other operations. How is that specific?
- 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);
- }
- }
- 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);
- 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;}
- }
In the above example, it is convenient to convert the JSON string into a list object, the operation of the time is more convenient ~
C # Serializes an object into a JSON string