0

I am relatively new to C# but as a test, I am trying to convert List to JSON but I get an empty JSON file. Can someone tell me what I am doing wrong?

I have a class Book

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;
    }
}

And this is my main class

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);
    }
}

Ans this is the output I am getting.

[{},{},{},{},{},{},{},{},{},{},{},{}]

Thanks in advance.

Zinox
  • 519
  • 9
  • 24

0 Answers0