i am Serializing a simple Object into JSON (this works fine) but i am having trouble deserializing that file and converting it into an Object.
This is the error: System.Text.Json.JsonException: ''S' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.'
This is the code:
public static T DeserializeJson<T>(string path) where T : new()
{
var options = new JsonSerializerOptions
{
WriteIndented = true,
IncludeFields = true
};
using (Stream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
if (File.Exists(path) && stream.Length > 0)
{
T obj = JsonSerializer.Deserialize<T>(stream.ToString(), options);
return obj;
}
else
{
T obj = new T();
JsonSerializer.SerializeAsync(stream, obj, options);
return obj;
}
}
}
And this is the class i am trying to serialize:
class Settings
{
[JsonInclude]
public int ScreenWidth { get; set; } = 1280;
[JsonInclude]
public int ScreenHeight { get; set; } = 800;
[JsonInclude] public bool IsFullScreen = false;
}
I haven't really worked with JSON before so i appologise if this is a dumb question.
Edit 1
So i was passing the stream
as a String in the JsonSerializer.Deserialize<T>
which was causing my issues, but how do i keep the "OpenOrCreate" functionality? (the post i've been linked to is reading the file using StreamReader but i may not have the file)