【问题标题】:Error reading JArray from JsonReader从 JsonReader 读取 JArray 时出错
【发布时间】:2018-01-31 14:27:56
【问题描述】:

以下方法通常有效,但有时会引发异常。我不知道为什么,因为它大部分时间都有效。也许是因为我使用美元符号将变量插入字符串。有人可以告诉我如何以不同的方式来避免错误吗?

我得到的异常:

Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader. Path '', line 0, position 0.'

方法:

public RetrieveModels(string path)
{
    JArray json = JArray.Parse(File.ReadAllText($@"{path}"));
    [...]
}

路径类似于:"C:\\Users\\ZAT\\source\\repos\\tool\\tool\\wwwroot\\processes.json"

我在控制器的以下Action方法中创建路径:

public IActionResult UploadFile(IFormFile file)
{
    if (file == null || file.Length == 0)
        return Content("file not selected");
    else
    {
        var path = Path.Combine(
                Directory.GetCurrentDirectory(), "wwwroot",
                "processes.json");

        using (var stream = new FileStream(path, FileMode.Create))
        {
            file.CopyToAsync(stream);
        }
        RetrieveModels rm = new RetrieveModels(path);
        [...]
    }
}

它也有可能在文件尚未创建或正在创建时尝试解析该文件。因此,我尝试将rm = new RetrieveModels(path); 放在file.CopyToAsync(stream); 下方,但这导致另一个异常说我无法访问该文件,因为它正在被另一个进程使用。

【问题讨论】:

  • 1) 请显示异常的完整ToString() 输出,包括异常类型、消息、回溯和内部异常(如果有)。 2) 尝试捕获异常并记录文件的前 200 个左右字符。 3) 顺便说一下,如果直接从流中加载,性能会更好,参见newtonsoft.com/json/help/html/ReadJson.htmnewtonsoft.com/json/help/html/Performance.htm#MemoryUsage
  • 或者你可以直接从IFormFile.OpenReadStream()返回的流中读取。并且可能在某些时候选择了错误的编码。但除此之外,这个问题中没有任何信息可供我们猜测问题。
  • 您确定文件中有 JSON,并且它包含一个 JSON 数组(以方括号 [] 开头和结尾)?如果文件为空,则可以解释您所看到的异常。
  • @dbc 感谢您的帮助。我想我解决了这个问题。看我的回答。
  • @BrianRogers 是的,我一直在使用相同的 json 文件,但很少有它不起作用。我通过使用asyncawait 解决了这个问题。我认为当我调用该方法时文件不会完全创建。看我的回答。

标签: c# asp.net .net asp.net-mvc json.net


【解决方案1】:

我想我通过使用asyncawait 解决了这个问题:

[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
    if (file == null || file.Length == 0)
        return Content("file not selected");
    else
    {                
        var path = Path.Combine(
                Directory.GetCurrentDirectory(), "wwwroot",
                "processes.json");

        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);

        }
        RetrieveModels rm = rm = new RetrieveModels(path);
        [...]
    }           
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多