1

Is there any way to read a JSON object from the stream where it's followed by other data, and thus the only way to find out that we should stop reading is by reaching the position where the object's opening brace is closed?

{
    "SomeData": "blahblah",
    "SubObject": {
        "SomeData": "blahblah}{{"
    }
}
... and some more text (not JSON)
dbc
  • 104,963
  • 20
  • 228
  • 340
user626528
  • 13,999
  • 30
  • 78
  • 146
  • Check [this](https://stackoverflow.com/questions/43747477/how-to-parse-huge-json-file-as-stream-in-json-net) You can use a similar approach. – Eldar Jan 18 '20 at 22:07
  • What do you mean by _and some more data_?. Once the braces are closed, json is done. Anything after that makes the document invalid – Jawad Jan 18 '20 at 22:26
  • 1
    If `... and some more data` *is not JSON* and you're using [tag:json.net] then you need to set `JsonSerializerSettings.CheckAdditionalContent = false` as shown in [Discarding garbage characters after json object with Json.Net](https://stackoverflow.com/a/37173878/3744182). – dbc Jan 18 '20 at 22:26
  • Either way might you please [edit] your question to clarify the content of `... and some more data` and the serializer you are using? – dbc Jan 18 '20 at 22:56
  • @dbc no it's not Json. – user626528 Jan 18 '20 at 23:01
  • Then if you're using [tag:json.net] the `CheckAdditionalContent = false` answers will work. – dbc Jan 18 '20 at 23:03

1 Answers1

0

I assume you're going to use Json.Net library. In this case it will cater for your particular use case out of the box.

consider the following:

    var s = "{ \"SomeData\": \"blahblah\", \"SubObject\": {\"SomeData\": \"blahblah}{{\"    } } sdfsdfsdf... and some more data";
    var obj1 = JsonConvert.DeserializeObject(s, new JsonSerializerSettings() {
        CheckAdditionalContent = false // this is the key here, otherwise you will get an exception
    });

    JsonSerializer serializer = new JsonSerializer();
    var obj2 = serializer.Deserialize(new JsonTextReader(new StringReader(s))); // no issues here either
timur
  • 14,239
  • 2
  • 11
  • 32