C# Json从流中反序列化多个对象

C# Json从流中反序列化多个对象,c#,json,json.net,C#,Json,Json.net,当json之间有其他文本时,如何从流中反序列化多个json对象。 在stream中,我有以下内容: Stuff that is not JSON {"a": 1, "b": 2} Stuff that is not JSON either {"a": 3, "b": 4} 我想解析这两个json对象。因为这不是一个本地json,所以您必须手动完成一些人工工作,尽管这应该不难 您可以将流传递到StreamReader并跳过前两行中的两行: var streamReader = new St

当json之间有其他文本时,如何从流中反序列化多个json对象。 在stream中,我有以下内容:

Stuff that is not JSON

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

Stuff that is not JSON either

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

我想解析这两个json对象。

因为这不是一个本地json,所以您必须手动完成一些人工工作,尽管这应该不难

您可以将流传递到
StreamReader
并跳过前两行中的两行:

var streamReader = new StreamReader(yourStream);

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

var jsonLine = textFile.ReadLine();
var yourObject = JsonConvert.Deserialize<dynamic>(jsonLine);
var streamReader=newstreamreader(yourStream);
对于(int i=0;i<2;i++)
{
streamReader.ReadLine();
}
var jsonLine=textFile.ReadLine();
var yourObject=JsonConvert.Deserialize(jsonLine);
这两条线都要这样做。如果有一个较长的JSON,行与行之间有一个常量,那么可以使用
while
循环,而不是使用模


注意:我解析为
dynamic
,尽管您可以将其解析为任何强类型。

感谢您的回复,但我想使用streams。阅读整行json会产生我想要避免的性能问题。(因为这些json行相当长)这是一个流。您可以使用
Read
替代
ReadLine
。你能给出一个更准确的例子吗?你的解决方案迫使我分配大字符串(整个json在一行上,它可能非常大)。我想使用
StreamReader
JsonTextReader
,但它们都是缓冲读取器,这意味着我不能交替使用它们。我的解决方案现在几乎可以工作了,它需要我实现非缓冲的“StreamReader”,然后在JsonTextReader中使用。我会在完成后发布。但也许有更好的办法,我明白了。你应该在你的问题中用大字串提到这个问题。