Additional text encountered after finished reading JSON content:
You need to surround that with square brackets, which denotes that it's an array:
[{"StaffID":"S01","StaffRank":"Manager"},{"StaffID":"S02","StaffRank":"Waiter"}]
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.