在.Net中内置了读写Json的对象就是 DataContractJsonSerializer 和 JavaScriptSerializer这两个。但是这个是在.Net 3.5之后才支持的。
要使用JavaScriptSerializer这个对象首先需要引用名称空间:
using System.Web.Script.Serialization;
下面是演示代码演示将C#对象和JSON的相互转换:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public
class Person
{ public
String Name { get ; set ; }
public
Int32 Age { get ; set ; }
public
Decimal Wage { get ; set ; }
} public
partial class _Default : System.Web.UI.Page
{ protected
void Page_Load( object
sender, EventArgs e)
{
JavaScriptSerializer sr = new
JavaScriptSerializer();
Person p = new
Person()
{
Name = "Job" ,
Age = 12,
Wage = 234
};
String result = sr.Serialize(p); //将一个p对象转换为JSON字符串
Response.Write(result + "<br/>" );
//将一个JSON字符串转换为C#对象
Person p1 = sr.Deserialize(result, p.GetType()) as
Person;
Response.Write(p1.Name + " "
+ p1.Age + " "
+ p1.Wage);
}
} |
运行结果为:
{"Name":"Job","Age":12,"Wage":234}
Job 12
234