版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35030499/article/details/82795933
接下来进行解析json,上一章中,把对象解析成了json文本,文本内容取决于对象包含什么内容,反过来,根据文本做对象,要有文本的模板,新建一个类与json文本相对应。
简单json文本解析.
JSON文本
[{"index":1,"studentName":"小明","sex":false,"books":[{"bookName":"崛起","prise":199},{"bookName":"提莫队长","prise":123}]},
{"index":2,"studentName":"小红","sex":true,"books":[{"bookName":"崛起","prise":199},{"bookName":"崛起","prise":199},{"bookName":"提莫队长","prise":123}]},
{"index":3,"studentName":"小李","sex":false,"books":[]}
]
对应类
跟上一章一样
[Serializable]
public class Student
{
public int index;
public string studentName;
public bool sex;
public Book[] books;
public Student()
{
}
public Student(int index, string studentName, bool sex, Book[] books)
{
this.index = index;
this.studentName = studentName;
this.sex = sex;
this.books = books;
}
}
[Serializable]
public class Book
{
public string bookName;
public int prise;
public Book() //有时不写默认构造 会报错
{
}
public Book(string bookName, int prise)
{
this.bookName = bookName;
this.prise = prise;
}
}
解析过程
解析可以多种方式,一种利用jsonDate ,一种利用T类型 ,后者方便一些
class Program
{
static void Main(string[] args)
{
#region Json读取测试
string json = File.ReadAllText(@"D:\VSProject\JSON\JSON\Json.json");
// Student[] sArray = JsonMapper.ToObject<Student[]>(json); //使用数组和list一样的结果
List<Student> sArray = JsonMapper.ToObject<List<Student>>(json);
foreach (Student st in sArray)
{
Console.Write(st.index + "-----------" + st.sex.ToString());
foreach (Book b in st.books)
{
Console.Write("-----------" +b.bookName + "-----------"+ b.prise);
}
Console.WriteLine();
}
#endregion
Console.ReadKey();
}
}