我阅读了几个类似的问题,但没有找到任何与 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 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
读取 XML 时忽略空格Ignore whitespace while reading XML(读取 XML 时忽略空格)
带有检查空元素的 XML 到 LINQXML to LINQ with Checking Null Elements(带有检查空元素的 XML 到 LINQ)
在 C# 中读取带有未闭合标签的 XMLReading XML with unclosed tags in C#(在 C# 中读取带有未闭合标签的 XML)
在 C# 中使用 Html 敏捷性解析表格、单元格Parsing tables, cells with Html agility in C#(在 C# 中使用 Html 敏捷性解析表格、单元格)
使用 LINQ 从 xml 中删除元素delete element from xml using LINQ(使用 LINQ 从 xml 中删除元素)
解析格式错误的 XMLParse malformed XML(解析格式错误的 XML)