gpt4 book ai didi

c# - JSON 反序列化异常 ('' S' 是值的无效开始)

转载 作者:行者123 更新时间:2023-12-05 04:52:59 25 4
gpt4 key购买 nike

我正在将一个简单的对象序列化为 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

所以我通过了 stream作为 JsonSerializer.Deserialize<T> 中的字符串这导致了我的问题,但我如何保留“OpenOrCreate”功能? (我链接到的帖子是使用 StreamReader 读取文件,但我可能没有该文件)

最佳答案

问题是您调用的 stream.ToString() 不会将流的内容转换为字符串。它只会返回 "System.IO.Stream"(这个确切的文本)。

既然你想维护OpenOrCreate功能,我建议围绕你的stream对象构造一个StreamReader,然后用它来读取文件内容:

using (Stream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
if (File.Exists(path) && stream.Length > 0)
{
// read the entire file using a `StreamReader`
string fileContents;
using (StreamReader reader = new StreamReader(stream))
{
fileContents = reader.ReadToEnd();
}
// deserialize the contents of the file
T obj = JsonSerializer.Deserialize<T>(fileContents, options);
return obj;
}
else
{
T obj = new T();
JsonSerializer.SerializeAsync(stream, obj, options);
return obj;
}
}

关于c# - JSON 反序列化异常 ('' S' 是值的无效开始),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66293560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com