JSON读取后遇到的其他文本

时间:2018-07-06 20:54:13

标签: c# json

我有这个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文件本身。有没有办法在我的代码中包装一些东西,使其读取正确的方式?谢谢。

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

如果这是您的PS C:\Users\Me> Invoke-RestMethod -Method Get -Uri "https://api.telegram.org/botTOKEN_HERE/getChat?chat_id=@publicId" ok result -- ------ True @{id=-YOUR_CHAT_ID; title=YOUR_CHAT_TITLE; username=YOUR_CHAT_USERNAME; type=supergroup; photo=} PS C:\Users\Me> 文件,则格式不正确...其中有多个json对象,但json中都没有包含这两个对象,以表明它是{ {1}}个对象,也不用逗号分隔。

这里最好的办法是一次读取一行,并将其转换为[]对象,因为似乎每一行都代表一个json对象。

json

答案 2 :(得分:0)

这是一种可以轻松修复该文件中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);
     }
 }