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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With