Load multiple concatenated JSON objects from stream(从流中加载多个连接的 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 流,所以我需要知道消息的大小才能读取它.我决定在每条消息之前用 size 和 message 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 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从流中加载多个连接的 JSON 对象
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
