1

I am trying to use Json.NET to parse a file of comma-separated JSON objects:

{
   JSON ...
},
{
   JSON ...
},
{
   JSON ...
}

The code below works fine if the stream contains no separators (i.e., commas above removed). However, commas produce an infinite loop where Json.NET keeps reading an "Undefined" token even after end of file was reached:

  using (StreamReader fReader = File.OpenText("filename.json"))
  using (JsonTextReader jReader = new JsonTextReader(fReader))
  {
    jReader.SupportMultipleContent = true;
    while (jReader.Read())
    {
      var jToken = JToken.ReadFrom(jReader);
      if (jToken is JObject)
        Console.WriteLine("JSON object: " + ((JObject)jToken).ToString());
    }
  }

I tried skipping the comma by reading ahead and using JsonTextReader's Skip() method, but this doesn't work: JsonTextReader apparently buffers ahead, eating up the comma, which gives it indigestion.

It's hard to believe that I'd be the first to run into this problem, but despite searching here for a good bit, I haven't found any relevant posts (at least for C# and Json.NET). Is it really necessary to hack this up from scratch?

ETA: As per Brian Rogers' comment below, Json.NET 11.0.1 and above handle comma-separated JSON, so the above works fine now, commas or not.

Paul Lambert
  • 420
  • 3
  • 10
  • 1
    Sounds like an [XY problem](http://xyproblem.info) to me. Better do not generate invalid JSON files at first place. – Uwe Keim Feb 03 '19 at 08:17
  • 1
    Yes, but these files come from an external source I do not control (I realize they're malformed). I would be more than happy to throw out my attempted solution if there's a superior approach. – Paul Lambert Feb 03 '19 at 08:21
  • 1
    Upgrade to Json.Net 11.0.1 or later. It supports what you are trying to do using the `SupportMultipleContent` setting on the reader. See the second answer of the linked duplicate question. – Brian Rogers Feb 03 '19 at 15:45

1 Answers1

1

One way to approach this would be make it a list. For example, you can add "[" "]" to either end of "comma separated Json" to convert it to a list and then deserialize it.

For example, consider the following code which has a Json Objects separated by Comma (for sake of simplicity, have created a simple json, but could work otherwise too)

var jsonString = @"{User:'anu viswan', Location:'India'},{User:'User2', Location:'India'}";

If you add "[" "]" to either end, and then serialize it, you could get a collection of RootObjects.

var result = JsonConvert.DeserializeObject<RootObject[]>($"[{jsonString}]");

In this particular case, RootObject is defined as

public class RootObject
{
    public string User { get; set; }
    public string Location { get; set; }
}

You can similarly convert the Json to a collection based on your Object definition.

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51