So, I'm reading a book about .NET Core 3 and I'm at a section where I'm learning how to serialize JSON files. I have run into a problem with types that I haven't been able to figure out a solution to. I have tried working around it, but then I run into other type issues. The problem I get with the code below is CS0029 in the last using statement of Main at File.Create(jsonPath)
:
Cannot implicitly convert type 'System.IO.FileStream' to 'System.IO.StreamWriter'
I have tried changing the using statement to use a FileStream type instead of a StreamWriter, as per the example I got from Microsoft documentation, but that produces an error at the jsonStream variable on the jsonSerializer.Serialize(jsonStream, people)
line that says:
Cannot convert from 'System.IO.FileStream' to 'System.IO.TextWriter
Here is the code below:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using Packt.Shared;
using static System.Console;
using static System.Environment;
using static System.IO.Path;
namespace WorkingWithSerialization
{
class Program
{
static void Main(string[] args)
{
List<Person> people = new List<Person>
{
new Person(30000M)
{
FirstName = "Adam",
LastName = "Smith",
DateOfBirth = new DateTime(1756,12,12)
},
new Person(40000M)
{
FirstName = "Lisa",
LastName = "Simpson",
DateOfBirth = new DateTime(1980,4,30)
},
new Person(20000M)
{
FirstName = "Barney",
LastName = "Rubble",
DateOfBirth = new DateTime(1962,7,14),
Children = new HashSet<Person>
{
new Person(0M)
{
FirstName = "Bob",
LastName = "Rubble",
DateOfBirth = new DateTime(1986,5,3)
},
new Person(0M)
{
FirstName = "Bamm-Bamm",
LastName = "Rubble",
DateOfBirth = new DateTime(1984,3,15)
}
}
}
};
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Person>));
string path = Combine(CurrentDirectory, "people.xml");
using(FileStream stream = File.Create(path))
{
xmlSerializer.Serialize(stream,people);
}
WriteLine($"Wrote {new FileInfo(path).Length} bytes to {path}.");
WriteLine($"\n{File.ReadAllText(path)}");
using(FileStream xmlLoad = File.Open(path, FileMode.Open))
{
List<Person> loadedPeople = (List<Person>)xmlSerializer.Deserialize(xmlLoad);
foreach(Person person in loadedPeople)
{
WriteLine($"{person.FirstName} has {person.Children.Count} children.");
}
}
string jsonPath = Combine(CurrentDirectory, "people.json");
using(StreamWriter jsonStream = File.Create(jsonPath))
{
var jsonSerializer = new Newtonsoft.Json.JsonSerializer();
jsonSerializer.Serialize(jsonStream, people);
}
}
}
}
I have also included the newest version of Newtonsoft.Json within the .csproj file, but I don't believe that to be the issue.
I have also tried different ways of casting with no positive results. I am unsure of what it is that I am doing wrong.