http://blog.163.com/hy_85/blog/static/1484587662011465235773/
以前要转json一般都是自己手工去写,再不济就是用Newtonsoft.Json.dll这个第三方的类库
今天突然发现.NET4.0里面自带了,这可真是一个伟大的发现
准备工作
需要引用
System.Web.Extensions.dll 这个类库
命名空间:
System.Web.Script.Serialization
|
|
|
数据结构
public class Team
{
public string Name { get; set; }
public List<User> Users { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
|
|
Class --> JSON
JavaScriptSerializer js = new JavaScriptSerializer();
Team team = new Team()
{
Name = "梦之队",
Users = new List<User>() {
new User() { Id = 1, Name = "XXX" },
new User() { Id = 2, Name = "YYY" },
new User() { Id = 3, Name = "ZZZ" },
}
};
string json = js.Serialize(team);
Console.WriteLine(json);
输出结果
|
|
|
Json --> Class
string json = "{\"Name\":\"梦之队\",\"Users\":[{\"Id\":1,\"Name\":\"XXX\"},{\"Id\":2,\"Name\":\"YYY\"},{\"Id\":3,\"Name\":\"ZZZ\"}]}";
JavaScriptSerializer js = new JavaScriptSerializer();
Team team = js.Deserialize<Team>(json);
结果:
|
|