//对象与数组转JSON
public static void GetJsonString()
{
//初始化对象
Obj product = new Obj() { Name = "苹果", Price = 5.5 };
//序列化
string o = new JavaScriptSerializer().Serialize(product);//值:"{\"Name\":\"苹果\",\"Price\":5.5}"
//数组转json
List<Obj> products = new List<Obj>(){
new Obj(){Name="苹果",Price=5.5},
new Obj(){Name="橘子",Price=2.5},
new Obj(){Name="干柿子",Price=16.00}
};
ProductList productlist = new ProductList();
productlist.GetProducts = products;
//序列化
string os = new JavaScriptSerializer().Serialize(productlist);
//输出 "{\"GetProducts\":[{\"Name\":\"苹果\",\"Price\":5.5},{\"Name\":\"橘子\",\"Price\":2.5},{\"Name\":\"干柿子\",\"Price\":16}]}"
}
//json转对象、数组, 反序列化
public static void JSONStringToList()
{
//json格式字符串
string JsonStr = "{Name:'苹果',Price:5.5}";
JavaScriptSerializer Serializer = new JavaScriptSerializer();
//json字符串转为对象, 反序列化
Obj obj = Serializer.Deserialize<Obj>(JsonStr);
Console.Write(obj.Name + ":" + obj.Price + "\r\n");
//json格式字符串
string JsonStrs = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]";
JavaScriptSerializer Serializers = new JavaScriptSerializer();
//json字符串转为数组对象, 反序列化
List<Obj> objs = Serializers.Deserialize<List<Obj>>(JsonStrs);
foreach (var item in objs)
{
Console.Write(item.Name + ":" + item.Price + "\r\n");
}
}