从流中加载多个连接的 JSON 对象

Load multiple concatenated JSON objects from stream(从流中加载多个连接的 JSON 对象)
本文介绍了从流中加载多个连接的 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了几个类似的问题,但没有找到任何与 JObject 相关的问题.这是问题所在:我有一个带有连接 JSON 对象的 Stream,即:

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 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)