Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Additional text encountered after finished reading JSON content:

Tags:

json

c#

json.net

I am having some problems with create with JSON.Net. When I try to parse it, it gives me following error:

Additional text encountered after finished reading JSON content:

I tried validating it with 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?

like image 512
Howard Hee Avatar asked May 27 '13 03:05

Howard Hee


2 Answers

You need to surround that with square brackets, which denotes that it's an array:

    [{"StaffID":"S01","StaffRank":"Manager"},{"StaffID":"S02","StaffRank":"Waiter"}]
like image 53
Kevin Schmid Avatar answered Nov 15 '22 17:11

Kevin Schmid


As of Release 11.0.1, Json.NET now natively supports parsing comma-delimited JSON in the same way it supports parsing newline delimited JSON:

New feature - Added support for reading multiple comma delimited values with JsonReader.SupportMultipleContent.

Thus the answer to Line delimited json serializing and de-serializing by Yuval Itzchakov should work here also. 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 a data model created to hold an individual item in the comma-separated list such as:

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

You can deserialize the JSON string shown like so:

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 comma-delimited objects from a large file, because it is not necessary to load the entire file into a string then add '[' and ']' to the beginning and end. In Performance Tips: Optimize Memory Usage Newtonsoft recommends deserializing large files directly from a stream, so instead a StreamReader can be passed into JsonExtensions.FromDelimitedJson() which will then stream through the file deserializing each object separately.

like image 8
dbc Avatar answered Nov 15 '22 15:11

dbc