【问题标题】:Cannot Deserialize JSON String in C#无法在 C# 中反序列化 JSON 字符串
【发布时间】:2021-05-31 12:47:07
【问题描述】:

我有以下型号:

public class InputFile
{
    public string Path { get; set; } // absolute path of file

    public string Content { get; set; } // full content of the json file
}

和

public class InputModel
{
    public List<InputFile> Files { get; set; }
}

我需要做的是从我的硬盘读取一堆 JSON 文件(大约 1000 个)并将它们转换为 InputModel 格式。 Path 是文件的绝对路径,Content 是文件内容。请注意,我只读取 JSON 文件,因此内容本身是 JSON 文件。这是代码:

public void Parse(string collectedInputPath) // Command Line Input
{
    List<string> directories = new List<string>();
    directories.Add(collectedInputPath);
    directories.AddRange(LoadSubDirs(collectedInputPath));
    InputModel input = new InputModel();
    string body = string.Empty;
    foreach(string directory in directories) // Going through all directories
    {                
        foreach (string filePath in Directory.GetFiles(directory)) // Adding every file to the Input Model List
        {
            string content = System.IO.File.ReadAllText(filePath);                    
            string fp = JsonConvert.SerializeObject(filePath);
            string jsonbody = JsonConvert.SerializeObject(content);                    
            body += $"{{\"Path\" : {filePath}, \"Content\": {content}}},";
        }
    }
    body += "]}";
    body = "{\"Files\":[" + body;                
    input = JsonConvert.DeserializeObject<InputModel>(body);
    Solve(input);
}

private List<string> LoadSubDirs(string dir)
{
    string[] subdirectoryEntries = Directory.GetDirectories(dir);
    List<string> subDirectoryList = new List<string>();
    foreach (string subDirectory in subdirectoryEntries)
    {
        subDirectoryList.Add(subDirectory);
        subDirectoryList.AddRange(LoadSubDirs(subDirectory));
    }

    return subDirectoryList;
}

collectedInputPath 是通过用户输入提供的根目录的路径。我必须检查根目录下的每个目录并读取每个 JSON 文件。 我收到此错误:

我应该如何纠正这个问题?

【问题讨论】:

  • 在反序列化之前打印出 JSON 字符串以验证它是否符合您的预期。
  • 您需要将内容编码为 JSON 值。看到这个:stackoverflow.com/questions/1242118/how-to-escape-json-string
  • @HansKilian 我正在将它们转换为我的 json 模型。我正在生成路径,提取内容,根据我的模型以 json 字符串文件的形式创建“body”字符串并尝试对其进行反序列化。并非所有文件都不是 JSON,但这不应该是问题。
  • @vernou 谢谢老兄!问题解决了!

标签: c# json file-handling json-deserialization json-serialization


【解决方案1】:

来自您的代码:

body += $"{{\"Path\" : {filePath}, \"Content\": {content}}},";

filePath 和 content 是字符串。因此,您在属性值周围缺少引号 "。即使你有它们,filePath 也可能包含反斜杠\,必须为 JSON 转义。目前,您的文件内容包含双引号 ",您的 JSON 字符串再次无效。

使用您的方法,您还创建了一个无效数组,因为您在添加到字符串的每个对象之后添加一个 ,,您的数组的最终字符串将如下所示 [{...}, {...},] 这是无效的JSON(可能有一些解析器接受尾随逗号,但严格来说是不允许的)

为什么还要手动创建 JSON 字符串,只是为了稍后再解析几行代码?只需直接填充您的模型...

InputModel input = new InputModel {
  Files = new List<InputFile>()
};
foreach(string directory in directories) // Going through all directories
{                
    foreach (string filePath in Directory.GetFiles(directory)) // Adding every file to the Input Model List
    {
        string content = System.IO.File.ReadAllText(filePath);                    
        var inputfile = new InputFile {
          Content = content, 
          Path = filePath
        };
        input.Files.Add(inputfile);
    }
}

【讨论】:

    猜你喜欢
    • 2021-02-26
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多