简体   繁体   English

处理 Json 多行反序列化

[英]Handling Json Deserialization with multiple lines

My application expects Json files coming in two different structure.我的应用程序期望 Json 文件有两种不同的结构。 One file where each line is a complete json and other file which is a Json file.一个文件,其中每一行是一个完整的 json 和其他文件是 Json 文件。 For ex: one file will have this structure例如:一个文件将具有这种结构

{"Logging": {"LogLevel": {"Default": "Warning", "System": "Warning", "Microsoft": "Warning" }}}

and other file with this structure:和其他具有这种结构的文件:

{"Logging": {"LogLevel": {"Default": "Warning",
      "System": "Warning",
      "Microsoft": "Warning"
    }}}

my below code does the deserialization and it works for first structure but fails for other file saying error as我下面的代码进行反序列化,它适用于第一个结构,但对于其他文件说错误失败

Unexpected end when reading token.读取令牌时意外结束。 Path ''."}小路 ''。”}

My code:我的代码:

foreach( var line in lines )
            {
   var data = JsonConvert.DeserializeObject<JObject>( line);}

I would like to know how can I fix this so that it handles files of both types?我想知道如何解决这个问题,以便它处理两种类型的文件?

You're reading each line of your JSON file into the data variable trying to parse each line.您正在将 JSON 文件的每一行读入尝试解析每一行的数据变量中。

So it tries to parse line 1, which is {"Logging": {"LogLevel": {"Default": "Warning", .因此它尝试解析第 1 行,即{"Logging": {"LogLevel": {"Default": "Warning", . and since that is not a valid JSON object the parsing fails.并且由于这不是有效的 JSON object 解析失败。

Instead use File.ReadAllText to read the entire file into a single string, then parse the string.而是使用File.ReadAllText将整个文件读入单个字符串,然后解析该字符串。 Or simply Join the string array back into a single string:或者简单地将字符串数组重新连接成一个字符串:

 var data = JsonConvert.DeserializeObject<JObject>(string.Join(Environment.NewLine,lines));}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM