无法在 C# 中反序列化 JSON 字符串

问题描述

我有以下型号:

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 文件。 我收到此错误:

Error Image

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

解决方法

来自您的代码:

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

filePathcontent 是字符串。因此,您缺少属性值周围的引号 "。即使您拥有它们,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);
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...