【发布时间】:2021-02-20 15:52:36
【问题描述】:
我正在将一个简单的对象序列化为 JSON(这工作正常),但我无法反序列化该文件并将其转换为对象。
这是错误:System.Text.Json.JsonException: ''S' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.'
这是代码:
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;
}
}
}
这是我要序列化的类:
class Settings
{
[JsonInclude]
public int ScreenWidth { get; set; } = 1280;
[JsonInclude]
public int ScreenHeight { get; set; } = 800;
[JsonInclude] public bool IsFullScreen = false;
}
我之前没有真正使用过 JSON,所以如果这是一个愚蠢的问题,我很抱歉。
编辑 1
所以我在JsonSerializer.Deserialize<T> 中将stream 作为字符串传递,这导致了我的问题,但我如何保留“OpenOrCreate”功能? (我链接到的帖子是使用 StreamReader 读取文件,但我可能没有文件)
【问题讨论】:
-
呃,
stream.ToString()将返回"System.IO.Stream",它不会将流的内容转换为字符串。 -
这与封闭通知中提到的问题不同。你能把你的数据文件的第一行贴出来吗?
-
@john 好的.. 我现在相信我需要眼镜.. 当
stream不适合该功能时,VS 可能会添加它。我的新问题是:如果我不能将stream传递给反序列化方法,我该如何保留“OpenOrCreate”功能?
标签: c# json serialization