Additional text received after completion of reading JSON content:

I am having some problems creating with JSON.Net. When I try to parse it, it throws the following error:

Extra text detected after reading JSON content:

I tried to check it using http://json.parser.online.fr/ and it says: "SyntaxError: unexpected token".

My JSON is as below:

{"StaffID":"S01","StaffRank":"Manager"},{"StaffID":"S02","StaffRank":"Waiter"} 

How to deserialize it?

+18
source share
2 answers

You need to surround this with square brackets, which means it's an array:

  [{"StaffID":"S01","StaffRank":"Manager"},{"StaffID":"S02","StaffRank":"Waiter"}] 
+25
source

Starting with Release 11.0.1, Json.NET now natively supports comma-separated JSON parsing, just as it supports JSON parsing:

New Feature - Added support for reading multiple values ​​separated by commas using JsonReader.SupportMultipleContent .

Thus, the answer to serialization and deserialization of json with line separators by Yuval Yitzhakov should work here as well. Define an extension method:

 public static partial class JsonExtensions { public static IEnumerable<T> FromDelimitedJson<T>(TextReader reader, JsonSerializerSettings settings = null) { using (var jsonReader = new JsonTextReader(reader) { CloseInput = false, SupportMultipleContent = true }) { var serializer = JsonSerializer.CreateDefault(settings); while (jsonReader.Read()) { if (jsonReader.TokenType == JsonToken.Comment) continue; yield return serializer.Deserialize<T>(jsonReader); } } } } 

Then, given the data model created to store a single item in the list, separated by a comma, for example:

 public class RootObject { public string StaffID { get; set; } public string StaffRank { get; set; } } 

You can deserialize the JSON string shown like this:

 var jsonString = @"{""StaffID"":""S01"",""StaffRank"":""Manager""},{""StaffID"":""S02"",""StaffRank"":""Waiter""}"; var list = JsonExtensions.FromDelimitedJson<RootObject>(new StringReader(jsonString)).ToList(); 

This approach may be preferable when deserializing a very large sequence of objects, separated by commas, from a large file, since there is no need to load the entire file into a string then add '[' and ']' to the beginning and end. Performance tips : optimize memory usage Newtonsoft recommends deserializing large files directly from a stream, so instead StreamReader can be passed to JsonExtensions.FromDelimitedJson() which will then go through the file, deserializing each object separately.

+2
source

All Articles