读取JSON时意外结束。路径”,第1行,位置1

时间:2018-12-09 07:28:48

标签: c# json json.net

我正在使用配置系统进行Minecraft帐户检查。 (请注意,检查器是用C#进行的,并且我将Newtonsoft.json用于配置系统)。 因此,我列出了一个列表:

List<string> config = File.ReadAllLines("config.json").ToList();

然后我编写了一个Parrallel.ForEach,其中包含该代码:

Parallel.ForEach(config, things =>
        {
            dynamic configJson = JsonConvert.DeserializeObject(things);

            int threads = (int)configJson.threads;
            string proxiesType = (string)configJson.proxiesType;

            Console.WriteLine(threads + " - " + proxiesType);
        });

config.json文件非常简单:

{
   "threads": 200,
   "proxiesType": "SOCKS5"
}

但是当我运行项目时,出现此错误:

  

Newtonsoft.Json.JsonSerializationException:'读取JSON时意外结束。路径”,第1行,位置1。'

我只需要帮助,因为我进行了搜索,但没有一个解决了这个问题。

2 个答案:

答案 0 :(得分:3)

我不知道您为什么要这样处理。没有理由使用Parallel.ForEach来解析JSON。

您现在正在做的是将JSON文件的每一行拖入列表,然后尝试解析每一行。

因此它尝试解析第1行,即{{不是有效的JSON对象。解析失败。

使用File.ReadAllText将整个文件读取为单个字符串,然后解析该字符串。不需要任何形式的循环。

答案 1 :(得分:2)

您可以通过两种方式使用Json.NET处理JSON文件:

  1. 使用丹尼尔(Daniel)建议的File.ReadAllText()
string json = File.ReadAllText("config.json");
Config config = JsonConvert.DeserializeObject<Config>(json);
  1. 使用直接在文件上打开的流。方法如下:
using (StreamReader file = File.OpenText("config.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    Config config = (Config)serializer.Deserialize(file, typeof(Config));
}
相关问题