C#中Newtonsoft.Json(Json.NET)的使用

时间:2021-11-17 05:16:13

C#中Newtonsoft.Json(Json.NET)的使用。

添加引用:

using Newtonsoft.Json; 

调用代码:

//获取图书列表
List<BookInfo> bookList = GetBookList();

//将图书列表转换成Json          
string bookListJson = JsonConvert.SerializeObject(bookList);

//将Json转换回图书列表
List<BookInfo> books = JsonConvert.DeserializeObject<List<BookInfo>>(bookListJson);

其他代码:

/// <summary>  
/// 图书信息实体类  
/// </summary>  
public class BookInfo
{
    public int BookId { set; get; }             //图书ID  
    public string Title { set; get; }           //图书名称  
    public string Category { set; get; }        //图书分类  
    public string Author { set; get; }          //图书作者  
    public DateTime PublishDate { set; get; }   //出版时间  
    public Double Price { set; get; }           //销售价格  
} 

/// <summary>  
/// 获取图书列表  
/// </summary>  
/// <returns></returns>  
public List<BookInfo> GetBookList()
{
    List<BookInfo> bookList = new List<BookInfo>();
    BookInfo book1 = new BookInfo()
    {
        BookId = 1,
        Category = "CHILDREN",
        Title = "Harry Potter",
        Author = "J K. Rowling",
        PublishDate = new DateTime(2005, 08, 15),
        Price = 29.99
    };
    bookList.Add(book1);
    BookInfo book2 = new BookInfo()
    {
        BookId = 2,
        Category = "WEB",
        Title = "Learning XML",
        Author = "Erik T. Ray",
        PublishDate = new DateTime(2003, 10, 18),
        Price = 39.95
    };
    bookList.Add(book2);
    return bookList;
}


相关文章