0

I'm new to C# and I want to read a .log file with json entries like this:

{
    "firstName": "John", "lastName": "Smith"
}

{
    "firstName": "Alice",
    "lastName": "Smith"
}

I want to parse from "{" to "}" to get the beginning and end of one entry.

I used:

StreamReader sr = new StreamReader(FileName);

logfile = sr.ReadLine();

var logentry = JsonConvert.DeserializeObject<dynamic>(logfile);

to deserialize the entry. It works well if the json entry is in one line. But the problem is that with ReadLine(), I can only read the json format in one line not multiple like the second example.

Maybe I could use ReadToEnd() and save it in a string and count the "{" and "}" and separate the entries.

dbc
  • 104,963
  • 20
  • 228
  • 340
Floorhahn
  • 1
  • 1
  • If you're in control of stopping logs being written across multiple lines, I recommend you get onto that. – ProgrammingLlama May 17 '21 at 08:25
  • If size is not an issue you could probably try reading the whole file and separating entries using `string.Split()` by using a sequence like `"}\n"`. Not particularly, fast, cheap, or durable, but may work like a charm depending on your data set. – DekuDesu May 17 '21 at 08:26
  • You could read the whole file and then use Regex to extract the json bits; https://stackoverflow.com/questions/21994677/find-json-strings-in-a-string – sommmen May 17 '21 at 08:47
  • Set [`JsonTextReader.SupportMultipleContent = true`](https://www.newtonsoft.com/json/help/html/ReadMultipleContentWithJsonReader.htm) as shown in [Line delimited json serializing and de-serializing](https://stackoverflow.com/q/29729063/3744182) and [Deserialize multiple json objects from a stream using Newtonsoft Json](https://stackoverflow.com/q/48882653/3744182). – dbc May 20 '21 at 18:34
  • Thanks https://www.newtonsoft.com/json/help/html/ReadMultipleContentWithJsonReader.htm is what is needed – Floorhahn Jun 04 '21 at 09:15

0 Answers0