Newtonsoft.Json用法

public partial class Json : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblContent.Text = Getjson();

List<Student> list = GetStu(lblContent.Text);

string ms = "{\"Id\":1,\"Name\":\"kai\"}";
Student s = GetOneStu(ms);
lblOne.Text = s.Name;
}

//获取json格式

public string Getjson()
{
List<Student> list = new List<Student>();
list.Add(new Student() { Name="kai",Id=1});
list.Add(new Student() { Name = "wan", Id = 2 });
list.Add(new Student() { Name = "lin", Id = 3 });

string json = JsonConvert.SerializeObject(list);
return json;
}
//返回单个实体类
public Student GetOneStu(string json)
{
JsonSerializer seria = new JsonSerializer();
StringReader r = new StringReader(json);
Student list = seria.Deserialize(new JsonTextReader(r), typeof(Student)) as Student;
return list;
}
//返回实体类集合
public List<Student> GetStu(string json)
{
JsonSerializer seria = new JsonSerializer();
StringReader r = new StringReader(json);
List<Student> list = seria.Deserialize(new JsonTextReader(r), typeof(List<Student>)) as List<Student>;
return list;
}

public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
}

posted @ 2016-10-14 10:43  开开123  阅读(425)  评论(0编辑  收藏  举报