【问题标题】:Additional text encountered after JSON reading读取 JSON 后遇到的附加文本
【发布时间】:2018-07-06 20:54:12
【问题描述】:

我有这个 JSON:

{"id":1,"name":"Alabama"}
{"id":2,"name":"Alaska"}
{"id":3,"name":"Arizona"}
{"id":4,"name":"Arkansas"}

还有这段代码:

string[] testDataFiles = new string[] { StatesOneFileName, StatesTwoFileName, ContinentsFileName };

foreach (var testFile in testDataFiles)
{
    using (StreamReader r = new StreamReader(testFile))
    {
        string json = r.ReadToEnd();
        dynamic jsonObjectArray = JsonConvert.DeserializeObject(json);

        foreach (var item in jsonObjectArray)
        {
            expectedPartitions.Add(item.name);
        }
    }
}

但是,当我运行它时,我得到了这个错误:

Additional text encountered after finished reading JSON content: {. Path '', line 2, position 0.

我已经阅读了一些 StackOverflow 建议以将测试数据包含在 [] 中,但不幸的是我无法编辑 json 文件本身。有没有办法在我的代码中包装一些东西,使它以正确的方式读取?谢谢。

【问题讨论】:

  • 不要让您进一步沮丧,但除了将这些行包含在 [ ] 括号中之外,您可能还需要在每一行的末尾添加一个逗号(最后一行除外)使其成为有效的 json 语法。
  • 糟糕,是的,@JoeIrby 是对的。请忽略我的第一条评论;)(现已删除)
  • 据我了解,如果您无法更改输入,则您有多个 Json 对象,然后分别解析每一行

标签: c# json


【解决方案1】:

假设文件每行包含一个json对象,如下:

{"id":1,"name":"Alabama"}
{"id":2,"name":"Alaska"}
{"id":3,"name":"Arizona"}
{"id":4,"name":"Arkansas"}

您可以为您的数据创建以下模型:

public class State
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("name")]
    public string Name{ get; set; }
}

然后创建一个简单的方法,逐行读取文件,如下:

public static IEnumerable<State> GetStates(string path)
{
    if (string.IsNullOrWhiteSpace(path))
    {
        throw new ArgumentException("Path to json file cannot be null or whitespace.", nameof(path));
    }

    if (!File.Exists(path))
    {
        throw new FileNotFoundException("Could not find json file to parse!", path);
    }

    foreach (string line in File.ReadLines(path).Where(x => !string.IsNullOrWhiteSpace(x)))
    {
        State state = JsonConvert.DeserializeObject<State>(line);

        yield return state;
    }
}

使用代码:

string path = ".....";

// get the list of State objects...
List<State> states = GetStates(path).ToList();

// or just the list of state names
List<string> stateNames = GetStates(path).Select(x => x.Name).ToList();

【讨论】:

    【解决方案2】:

    如果这是您的 json 文件,则它的格式不正确...您在其中有多个 json 对象,但它既没有包含在 [] 中以表明它是 json 对象的数组,也不是它们用逗号分隔。

    您可以在这里做的最好的事情是一次读取一行,并将其转换为json 对象,因为每一行似乎代表一个json 对象。

    string json = "start";
    using (StreamReader r = new StreamReader(testFile)) {
        while (!String.IsNullOrWhiteSpace(json)){
          json = r.ReadLine();
          dynamic jsonObject = JsonConvert.DeserializeObject(json);
          //DO YOUR MAGIC HERE
         }
     }
    

    【讨论】:

    • 或者您可以使用var names = File.ReadLines(testFile).Select(line =&gt; JObject.Parse(line)["name"])以更简洁的方式执行此操作
    【解决方案3】:

    这是一种方法,您可以轻松地从该文件修复 json 中的语法错误,而无需过多地修改现有代码:

    foreach (var testFile in testDataFiles)
     {
         // read the contents of the file with invalid json format, and build a new string named cleanJson with the fixed file contents
         string[] fileLines = File.ReadAllLines(testFile);
         string cleanJson = "["; // add an opening array bracket to make it valid json syntax
         for (int i = 0; i < fileLines.Length; i++)
         {
             cleanJson += fileLines[i];
             if (i < fileLines.Length - 1)
                  cleanJson += ","; // add a comma to the end of each line (except the last) to make it valid json syntax
         }
         cleanJson += "]"; // add a closing array bracket to make it valid json syntax
    
         dynamic jsonObjectArray = JsonConvert.DeserializeObject(cleanJson);
    
         foreach (var item in jsonObjectArray)
         {
             expectedPartitions.Add(item.name);
         }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2014-08-07
      相关资源
      最近更新 更多