简体   繁体   中英

Handling Json Deserialization with multiple lines

My application expects Json files coming in two different structure. One file where each line is a complete json and other file which is a Json file. 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.

So it tries to parse line 1, which is {"Logging": {"LogLevel": {"Default": "Warning", . and since that is not a valid JSON object the parsing fails.

Instead use File.ReadAllText to read the entire file into a single string, then parse the string. Or simply Join the string array back into a single string:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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