10.6.4 Json文件操作

版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。

Json格式作为轻量级数据交换格式,在网页上也得到大量应用。Json格式与XML格式各有优缺点,本书中不作讨论,请自行查找相关资料。

在实际使用Json时,需要对它进行序列化或者反序列化。所谓序列化就是将对象转换为Json字符串;而反序列化就是将Json格式字符串转换为指定类型的对象。

C#中支持对Json序列化和反序列化的类有两个:JavaScriptSerializer类和DataContractJsonSerializer类。其中:

JavaScriptSerializer类需要引用System.Web.Extensions程序集,然后在所有代码前加上:

using System.Web.Script.Serialization;

DataContractJsonSerializer类需要引用System.Runtime.Serialization程序集,然后在所有代码前加上:

using System.Runtime.Serialization.Json;

具体的引用方法是,单击菜单【项目】|【添加引用】,弹出【引用管理器】窗口,单击【程序集】|【框架】,从中间部分找到并勾选相应的程序集名称,最后按下"确定"按钮即可。

本节教程使用到用来序列化和反序列化的类:

public class Book

{

public string ISBN;

public string Title;

public float Price;

public string Year;

}

public class BookStore

{

public Book book;

}

public class Books

{

public BookStore bookstore;

}

public class BookStoreArray

{

public Book book;

}

public class BooksArray

{

public string Name;

public BookStoreArray[] bookstore;

}

**注意:**在将类对象序列化为Json字符串时,类对象成员变量的名称将转为Json中的数据名称,类对象成员变量相应的值转为Json中的数据值。反序列化时,定义类对象成员变量的名称需要和Json中的数据名称一致,否则不能获取对应的数据值。

10.6.4.1 JavaScriptSerializer类

JavaScriptSerializer类为Json(启用AJAX的应用程序)提供序列化和反序列化功能。

JavaScriptSerializer重要方法:

  1. Serialize:序列化,将对象转换为Json字符串。
  2. Deserialize:反序列化,将Json格式字符串转换为指定类型的对象。

【例 10.27 【项目:code10-027】使用JavaScriptSerializer生成和解析Json格式。

//序列化

private void Button1_Click(object sender, EventArgs e)

{

Books newbooks = new Books();

BookStore newBook = new BookStore();

Book newSingleBook = new Book();

newSingleBook.ISBN = "9787302425274";

newSingleBook.Title = "星球大战:克隆人的进攻";

newSingleBook.Price = 48.0f;

newSingleBook.Year = "1985";

newBook.book = newSingleBook;

newbooks.bookstore = newBook;

//声明并实例化JavaScriptSerializer

JavaScriptSerializer serializer = new JavaScriptSerializer();

string strNewBook;

//序列化,将Books类对象转为Json字符串

strNewBook = serializer.Serialize(newbooks);

//显示序列化后的结果

textBox1.Text = strNewBook;

}

//反序列化

private void Button2_Click(object sender, EventArgs e)

{

//声明并实例化JavaScriptSerializer

JavaScriptSerializer serializer = new JavaScriptSerializer();

string strNewBook = textBox1.Text;

Books newBooks = new Books();

//反序列化,将Json字符串转换为Books类对象

newBooks = serializer.Deserialize<Books>(strNewBook);

textBox2.Text += "---------------" + "\r\n";

textBox2.Text += "ISBN:" + newBooks.bookstore.book.ISBN + "\r\n";

textBox2.Text += "Title:" + newBooks.bookstore.book.Title + "\r\n";

textBox2.Text += "Price:" + newBooks.bookstore.book.Price + "\r\n";

textBox2.Text += "Year:" + newBooks.bookstore.book.Year + "\r\n";

}

//序列化数组

private void Button3_Click(object sender, EventArgs e)

{

BooksArray newBooks = new BooksArray();

newBooks.Name = "星球大战系列";

newBooks.bookstore= new BookStoreArray[3];

Book newSingleBook = new Book();

newSingleBook.ISBN = "9787302425274";

newSingleBook.Title = "星球大战:克隆人的进攻";

newSingleBook.Price = 48.0f;

newSingleBook.Year = "1985";

BookStoreArray newBook = new BookStoreArray();

newBook.book = newSingleBook;

newBooks.bookstore[0] = newBook;

newSingleBook = new Book();

newSingleBook.ISBN = "9787302426899";

newSingleBook.Title = "星球大战:西斯的复仇";

newSingleBook.Price = 58.0f;

newSingleBook.Year = "1985";

newBook = new BookStoreArray();

newBook.book = newSingleBook;

newBooks.bookstore[1] = newBook;

newSingleBook = new Book();

newSingleBook.ISBN = "99787302421146";

newSingleBook.Title = "星球大战:新的希望";

newSingleBook.Price = 35.0f;

newSingleBook.Year = "1985";

newBook = new BookStoreArray();

newBook.book = newSingleBook;

newBooks.bookstore[2] = newBook;

JavaScriptSerializer serializer = new JavaScriptSerializer();

string strNewBook;

strNewBook = serializer.Serialize(newBooks);

textBox1.Text = strNewBook;

}

//反序列化数组

private void Button4_Click(object sender, EventArgs e)

{

JavaScriptSerializer serializer = new JavaScriptSerializer();

string strNewBook = textBox1.Text;

BooksArray newBooks = new BooksArray();

newBooks = serializer.Deserialize<BooksArray>(strNewBook);

textBox2.Text += newBooks.Name + "\r\n";

for(int i = 0;i<= newBooks.bookstore.Length - 1;i++)

{

textBox2.Text += "---------------" + "\r\n";

textBox2.Text += "ISBN:" + newBooks.bookstore[i].book.ISBN + "\r\n";

textBox2.Text += "Title:" + newBooks.bookstore[i].book.Title + "\r\n";

textBox2.Text += "Price:" + newBooks.bookstore[i].book.Price + "\r\n";

textBox2.Text += "Year:" + newBooks.bookstore[i].book.Year + "\r\n";

}

}

运行结果如下图所示:

图10-16 序列化和反序列化Json数组

10.6.4.2 DataContractJsonSerializer类

DataContractJsonSerializer类将对象序列化为 Json数据,或将Json数据反序列化为对象。

DataContractJsonSerializer构造函数其中一个重载版本:

public DataContractJsonSerializer(Type type )

参数说明:

  1. type:表示序列化或反序列化的实例的类型。在实际使用中可以使用typeof(类型)方法来获取。

DataContractJsonSerializer常用方法:

  1. WriteObject:将指定对象序列化为Json数据,其中一个重载版本:

public override void WriteObject(Stream stream, Object graph );

  1. stream:要写入的流。
  2. graph:包含要写入流的数据的对象。
  1. ReadObject:读取Json格式流,并返回反序列化的对象。其中一个重载版本:

public override Object ReadObject(Stream stream);

  1. stream:要读取的Stream。

【例 10.28 【项目:code10-028】使用DataContractJsonSerializer生成和解析Json格式。

//序列化

private void Button1_Click(object sender, EventArgs e)

{

Books newbooks = new Books();

BookStore newBook = new BookStore();

Book newSingleBook = new Book();

newSingleBook.ISBN = "9787302425274";

newSingleBook.Title = "星球大战:克隆人的进攻";

newSingleBook.Price = 48.0f;

newSingleBook.Year = "1985";

newBook.book = newSingleBook;

newbooks.bookstore = newBook;

//使用GetType方法获得Books的Type对象

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Books));

System.IO.MemoryStream ms = new System.IO.MemoryStream();

//将指定对象序列化为Json数据并写入流

serializer.WriteObject(ms, newbooks);

Byte[] json;

json = ms.ToArray();

ms.Close();

///将字节数组按照编码转换为字符串

string strNewBook = System.Text.Encoding.UTF8.GetString(json);

textBox1.Text = strNewBook;

}

//反序列化

private void Button2_Click(object sender, EventArgs e)

{

string strNewBook =textBox1.Text;

Books newBooks = new Books();

DataContractJsonSerializer serializer=new DataContractJsonSerializer(typeof(Books));

Byte[] bteNewBook;

bteNewBook = System.Text.Encoding.UTF8.GetBytes(strNewBook);

System.IO.MemoryStream ms = new System.IO.MemoryStream(bteNewBook);

newBooks = (Books)serializer.ReadObject(ms);

textBox2.Text += "---------------" + "\r\n";

textBox2.Text += "ISBN:" + newBooks.bookstore.book.ISBN + "\r\n";

textBox2.Text += "Title:" + newBooks.bookstore.book.Title + "\r\n";

textBox2.Text += "Price:" + newBooks.bookstore.book.Price + "\r\n";

textBox2.Text += "Year:" + newBooks.bookstore.book.Year + "\r\n";

}

//序列化数组

private void Button3_Click(object sender, EventArgs e)

{

BooksArray newBooks = new BooksArray();

newBooks.Name = "星球大战系列";

newBooks.bookstore = new BookStoreArray[3];

Book newSingleBook = new Book();

newSingleBook.ISBN = "9787302425274";

newSingleBook.Title = "星球大战:克隆人的进攻";

newSingleBook.Price = 48.0f;

newSingleBook.Year = "1985";

BookStoreArray newBook = new BookStoreArray();

newBook.book = newSingleBook;

newBooks.bookstore[0] = newBook;

newSingleBook = new Book();

newSingleBook.ISBN = "9787302426899";

newSingleBook.Title = "星球大战:西斯的复仇";

newSingleBook.Price = 58.0f;

newSingleBook.Year = "1985";

newBook = new BookStoreArray();

newBook.book = newSingleBook;

newBooks.bookstore[1] = newBook;

newSingleBook = new Book();

newSingleBook.ISBN = "99787302421146";

newSingleBook.Title = "星球大战:新的希望";

newSingleBook.Price = 35.0f;

newSingleBook.Year = "1985";

newBook = new BookStoreArray();

newBook.book = newSingleBook;

newBooks.bookstore[2] = newBook;

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(BooksArray));

System.IO.MemoryStream ms = new System.IO.MemoryStream();

serializer.WriteObject(ms, newBooks);

Byte[] json;

json = ms.ToArray();

ms.Close();

string strNewBook = System.Text.Encoding.UTF8.GetString(json);

textBox1.Text = strNewBook;

}

//反序列化数组

private void Button4_Click(object sender, EventArgs e)

{

string strNewBook = textBox1.Text;

BooksArray newBooks = new BooksArray();

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(BooksArray));

Byte[] bteNewBook;

bteNewBook = System.Text.Encoding.UTF8.GetBytes(strNewBook);

System.IO.MemoryStream ms =new System.IO.MemoryStream(bteNewBook);

newBooks = (BooksArray)serializer.ReadObject(ms);

textBox2.Text = newBooks.Name + "\r\n";

for (int i = 0; i <= newBooks.bookstore.Length - 1; i++)

{

textBox2.Text += "---------------" + "\r\n";

textBox2.Text += "ISBN:" + newBooks.bookstore[i].book.ISBN + "\r\n";

textBox2.Text += "Title:" + newBooks.bookstore[i].book.Title + "\r\n";

textBox2.Text += "Price:" + newBooks.bookstore[i].book.Price + "\r\n";

textBox2.Text += "Year:" + newBooks.bookstore[i].book.Year + "\r\n";

}

}

运行结果同【例 10.27】。

学习更多vb.net知识,请参看vb.net 教程 目录

学习更多C#知识,请参看C#教程 目录

相关推荐
思逻辑维2 小时前
强大到工业层面的软件
数据结构·sql·sqlite·json
的不对不6 小时前
WPF基础03——InitializeComponent()函数解释
windows·c#·.net·wpf
步、步、为营7 小时前
C#牵手Blazor,解锁跨平台Web应用开发新姿势
开发语言·前端·c#
一念春风7 小时前
C# 小说阅读 文本文件阅读
c#
VB.Net10 小时前
10.3 文件操作
c#·教程
旺代11 小时前
Qt中json的使用
qt·json
VB.Net11 小时前
10.6.1 文本文件读、写和追加
c#
玉面小君14 小时前
适合 C# 开发者的 Semantic Kernel 入门:用 AI 赋能你的 .NET 应用
人工智能·c#·.net
军训猫猫头17 小时前
61.异步编程1 C#例子 WPF例子
开发语言·c#·wpf