我对C#比较新,但作为测试,我试图将List转换为JSON,但我得到一个空的JSON文件。有人能告诉我我做错了什么吗?
我有一本班级书
class Book
{
string _title { get; set; }
string _author { get; set; }
public Book() { }
public Book(string title = "",
string author = "")
{
_title = title;
_author = author;
}
public override string ToString()
{
string info = $"Title: {_title} by {_author}";
return info;
}
}
这是我的主要课程
static void Main(string[] args)
{
string path = @"C:\Users\Zinox\Desktop\xml\";
string xmlPath = path + "books.xml";
string listJson = path + "Booklist.json";
string openFile = File.ReadAllText(xmlPath);
Book book = new Book();
List<Book> booklist = new List<Book>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(openFile);
XmlNode root = doc.DocumentElement;
foreach (XmlNode b in root)
{
booklist.Add(new Book(
b.SelectSingleNode("title").InnerText,
b.SelectSingleNode("author").InnerText
));
}
string listData = JsonConvert.SerializeObject(booklist,
Newtonsoft.Json.Formatting.None);
File.WriteAllText(listJson, listData);
}
}
这是我得到的输出。
[{},{},{},{},{},{},{},{},{},{},{},{}]
提前致谢。