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));}