Method of Serialization and Deserialization of JSON String by C

  • 2021-11-24 02:34:26
  • OfStack

C # Serializes an object into an JSON string


public string GetJsonString() 
{ 
 List<Product> products = new List<Product>(){ 
 new Product(){Name=" Apple ",Price=5}, 
 new Product(){Name=" Orange ",Price=5}, 
 new Product(){Name=" Dried persimmon ",Price=00} 
 }; 
 ProductList productlist = new ProductList(); 
 productlistGetProducts = 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; } 
} 

Here, we mainly use JavaScriptSerializer to implement serialization operation, so that we can convert objects into strings in Json format, and the resulting results are as follows:


{"GetProducts":[{"Name":" Apple ","Price":5},{"Name":" Orange ","Price":5},{"Name":" Persimmon ","Price":16}]}

How to convert Json strings into objects for use?

In actual development, it is often possible to pass a string in Json format to the background with JS. If the string can be automatically converted into the desired object, it is much more convenient to traverse or other operations. How is it realized?


public static List<T> JSONStringToList<T>(this string JsonStr) 
{ 
 JavaScriptSerializer Serializer = new JavaScriptSerializer(); 
 List<T> objs = SerializerDeserialize<List<T>>(JsonStr); 
 return objs; 
} 
 
public static T Deserialize<T>(string json) 
{ 
 T obj = ActivatorCreateInstance<T>(); 
 using (MemoryStream ms = new MemoryStream(EncodingUTFGetBytes(json))) 
 { 
 DataContractJsonSerializer serializer = new DataContractJsonSerializer(objGetType()); 
 return (T)serializerReadObject(ms); 
 } 
} 
 
string JsonStr = "[{Name:' Apple ',Price:5},{Name:' Orange ',Price:5},{Name:' Persimmon ',Price:16}]"; 
List<Product> products = new List<Product>(); 
products = JSONStringToList<Product>(JsonStr); 
 
foreach (var item in products) 
{ 
 ResponseWrite(itemName + ":" + itemPrice + "<br />"); 
} 
 
public class Product 
{ 
 public string Name { get; set; } 
 public double Price { get; set; } 
} 

In the above example, it is very convenient to convert Json string into List object, which is much more convenient to operate ~


Related articles: