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

标签 c# json serialization

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

相关文章:

javascript - Ajax - 处理大量数据的最佳技术

c# - 无论如何让 JsonConvert.SerializeObject 忽略属性上的 JsonConverter 属性?

c - 序列化其中包含 union 和结构的结构

c# - C#中的树数据结构

c# - 了解 Dappers splitOn 属性

javascript - D3 : Grayscale image display driven by 2D array data

javascript - 无法读取未定义的属性 'Drivers'

java - Objective-C : Serializing/Archiving issues

c# - 在 C# 中,改进单元测试反馈循环的好方法是什么?

c# - NHibernate 何时使用延迟加载?