Json.NET简单使用
引用命名空间:
using Newtonsoft.Json;
实体类:
代码
public class User
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public string Email
{
get;
set;
}
public string Addr
{
get;
set;
}
public class User
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public string Email
{
get;
set;
}
public string Addr
{
get;
set;
}
Object to Json:
代码
IList<User> list = new List<User>();
for (int i = 0; i < 10; i++)
{
User user = new User { Id = i, Name = "name" + i.ToString(), Addr = "address" + i.ToString(), Email = "email" + i.ToString() };
list.Add(user);
}
string json = JsonConvert.SerializeObject(list);
for (int i = 0; i < 10; i++)
{
User user = new User { Id = i, Name = "name" + i.ToString(), Addr = "address" + i.ToString(), Email = "email" + i.ToString() };
list.Add(user);
}
string json = JsonConvert.SerializeObject(list);
Json to Object:
代码
string str = "[{\"Id\":0,\"Name\":\"name0\",\"Email\":\"email0\",\"Addr\":\"address0\"},{\"Id\":1,\"Name\":\"name1\",\"Email\":\"email1\",\"Addr\":\"address1\"}]";
var obj = JsonConvert.DeserializeObject<IList<User>>(str);
var obj = JsonConvert.DeserializeObject<IList<User>>(str);