Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

c# - Load multiple concatenated JSON objects from 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"}

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 ...
}

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Read Multiple Fragments With JsonReader

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...