在C# 中 object 转化 Json

要将C#object类型值转换成成有效的Json值,我们可以从这个命名空间中调用方法:
System.Web.Script.Serialization.JavaScriptSerializer,
它存在于.Net FrameWord 3.5框架中的System.Web.Extentions的DLL中.

我们在C#中使用它的序列话对象和反序列化对象.
下面是个快速对象:

一个简单的 Employee 实体类,

public class Employee
{
public string Name { get; set; }
public string Age { get; set; }
public string ID { get; set; }
}

添加一些对象到一个范型,

mployee oEmployee1 =  new Employee{Name="Pini",ID="111", Age="30"};

Employee oEmployee2 = new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" };

Employee oEmployee3 = new Employee { Name = "Yoni", ID = "Biton", Age = "20" };

List<Employee> oList = new List<Employee>() { oEmployee1, oEmployee2, oEmployee3 };

这时我们转化这个范型:

System.Web.Script.Serialization.JavaScriptSerializer oSerializer = 
new System.Web.Script.Serialization.JavaScriptSerializer();

string
sJSON = oSerializer.Serialize(oList);

这时打印出的结果如下:

[{"Name":"Pini","Age":"30","ID":"111"},
{"Name":"Yaniv","Age":"31","ID":"Cohen"},
{"Name":"Yoni","Age":"20","ID":"Biton"}]

你可能感兴趣的:(object)