从流中加载多个串联的JSON对象 [英] Load multiple concatenated JSON objects from stream

查看:104
本文介绍了从流中加载多个串联的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了几个类似的问题,但是没有找到任何与JObject相关的问题.问题出在这里:我有一个带有串联JSON对象的流,即:

I read a couple of similar questions but didn't find any one related to JObject. Here's the problem: I have a Stream with concatenated JSON objects, i.e:

{"key1":"value1"}{"key2":"value2"}{"key3":"value3"}

现在,我想将这些对象一一读入JObject.这是我尝试执行的操作:

Now, I want to read these objects one by one into JObject. Here's how I tried to do it:

public class JsonStreamReader : JsonTextReader
{
    public JsonStreamReader(Stream s) : base(new StreamReader(s)) {}
}

private void LoadJson(Stream s)
{
    var r = new JsonStreamReader(s) { SupportMultipleContent = true };
    var obj = JObject.Load(r);
    // ... get data from JObject ...
}

这里的问题是JObject.Load()从流中读取所有可用数据,但仅解析第一个对象,而丢弃其余所有对象. 我该如何处理?

The problem here is that JObject.Load() reads all available data from stream, but parses only first object and discards all the rest. How do I deal with that?

以防出现XY问题(为什么需要这样做): 我想通过TCP流传输JSON消息.因为我使用原始TCP流,所以我需要知道读取消息的大小.我决定在每条消息之前用sizemessage type编写小标头,这样我可以将标头读到一个小缓冲区中,获取以下消息的大小,然后完整地读取它.

And just in case of XY-problem (why do I need that): I want to transfer JSON messages via TCP stream. Because I use raw TCP stream, I need to know the size of message to read it. I decided to write small header with size and message type before each message, so I can read the header into a small buffer, get the size of the following message and then read it entirely.

推荐答案

您可以通过将JsonReader上的SupportMultipleContent设置为true来做到这一点:

You can do that by setting SupportMultipleContent on JsonReader to true:

使用JsonReader读取多个片段

如果在该设置下使用JObject.Load时遇到问题,请改用JsonConvert.DeserializeObject.

If there is an issue with using JObject.Load with that setting then use JsonConvert.DeserializeObject instead.

这篇关于从流中加载多个串联的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆