0

Is it possible to serialize object collection in a way that we get one JSON object per line? Like this:

{tag1: value1, tag2: value2}, 
{tag1: value3, tag2: value6}, 
{tag1: value4, tag2: value7}, 
{tag1: value5, tag2: value8}

As I know, I can serialize to have "pretty" and indented JSON or one-line JSON, which is not what I need.

Loreno
  • 668
  • 8
  • 26
  • Is there a particular reason for that? It seems like an unusual requirement. One simple option could be to do a little string manipulation after your JSON has been produced – Martin Jul 30 '19 at 13:37
  • Why not trim the Square brackets after serialization? For example, JsonConvert.SerializeObject(collection).Trim('[').Trim(']') – Anu Viswan Jul 30 '19 at 13:39
  • You're going to have to do this manually, serialize each object and build the lines yourself. This is not JSON or any other known format so you don't have library help for this. – Lasse V. Karlsen Jul 30 '19 at 14:35
  • @Martin I have an application where I need a way to read, for example, just 100 objects from a file that has maybe 1000000 of them. I need that because I don't want to exhaust the memory. So, I thought I would store my JSONs in a file in a way that is easy to read - if I want 500 objects, I read 500 lines. Then, next 500 - next 500 lines. Do you think there is a better solution? Well, I'm sure there is, but I don't see it. – Loreno Jul 30 '19 at 15:39
  • If you were to remove the comma from the end of each line, what you have is "json lines format", there could be nuget packages for this. – Lasse V. Karlsen Jul 30 '19 at 16:03
  • Related: [Serialize as NDJSON using Json.NET](https://stackoverflow.com/q/44787652/3744182). – dbc Jul 30 '19 at 22:43

1 Answers1

2

It sounds like you want newline-delimited JSON. It's the same as what you have in your question but without the trailing commas.

You can make a simple helper method to create this format using Json.Net like this:

public static string Serialize(IEnumerable items)
{
    StringBuilder sb = new StringBuilder();
    foreach (var item in items)
    {
        sb.AppendLine(JsonConvert.SerializeObject(item));
    }
    return sb.ToString();
}

Better yet, just stream the items directly to your file:

public static void SerializeToFile(IEnumerable items, string fileName, bool append = true)
{
    using (StreamWriter sw = new StreamWriter(fileName, append))
    using (JsonWriter writer = new JsonTextWriter(sw))
    {
        var ser = new JsonSerializer();
        foreach (var item in items)
        {
            ser.Serialize(writer, item);
            writer.WriteWhitespace(Environment.NewLine);
        }
    }
}
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300