ppiotrowicz
ppiotrowicz

Reputation: 4614

Newtonsoft.Json deserializing multiple objects from stream

How can I deserialize multiple json objects from stream, when there's other text between jsons. In stream I have the following content:

Stuff that is not JSON

{"a": 1, "b": 2}

Stuff that is not JSON either

{"a": 3, "b": 4}

I would like to parse out those two json objects.

Upvotes: 3

Views: 959

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149636

Since this isn't a native JSON, you're going to have to do some labor work manually, though it shouldn't be difficult.

You can pass your stream into a StreamReader and skip two the first two lines:

var streamReader = new StreamReader(yourStream);

for (int i = 0; i < 2; i++)
{
    streamReader.ReadLine();
}

var jsonLine = textFile.ReadLine();
var yourObject = JsonConvert.Deserialize<dynamic>(jsonLine);

Do this for both the lines. If you have a longer JSON with a constant between the lines, you can use a while loop instead with a modulo.

Note i parsed to dynamic, though you can parse this into any strongly typed type you have.

Upvotes: 1

Related Questions