Deserialize single/multiple JSON objects into C# - Issues with single objects

sryan2k1

Ars Legatus Legionis
46,877
Subscriptor++
So I'm whipping up something quick and dirty for a work project. I've got a C# class that is all string types, nothing fancy, and once the item is created it gets serialized with the new System.Text.Json stuff and then attempts to POST to a web server. If that POST fails I write the data to a log file that has today's date as the name. If the file exists I need to append to the file.

All pretty straight forward right?


If today's file does not exist writing the object out is easy:

Code:
File.WriteAllText(path, JsonSerializer.Serialize(rpt, options), Encoding.UTF8);

In this case "rpt" is a single item of my class, this writes the JSON file correctly. I have also tried serializing a List<> of my class and the serializer builds the output correctly. All good so far!


Now my issue comes when dealing with appending objects to my file. Because I need valid JSON I can't just add the single item to the existing text file because that isn't valid.


The code I came up with for appending the items is as follows:

Code:
List<Report> reports = JsonSerializer.Deserialize<List<Report>>(File.ReadAllText(path, Encoding.UTF8));
reports.Add(rpt);
File.WriteAllText(path, JsonSerializer.Serialize(reports, options), Encoding.UTF8);

This works great if the JSON file it reads contains an array (2+ items) and correctly appends the new item.

However if this tries to read a file with a single item in it, it blows up with this:

System.Text.Json.JsonException: 'The JSON value could not be converted to System.Collections.Generic.List`1[TelemetryCollector.Report]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.'


I will admit I haven't dabbled in this stuff in a while and I might be missing something completely obvious. Any ideas on how to do this perhaps a better way? Why isn't the deserializer returning a list of 1?
 

sryan2k1

Ars Legatus Legionis
46,877
Subscriptor++
Of course once I post this I had a kind of lightbulb moment. When writing a new file just write a List<> of a single item, and then the serilizer creates the JSON array and not a single item.


Still, I'm curious why the deserilizer isn't smart enough to deal with a single item although I'm guessing it has to do with some of the List<Class> voodoo.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
First things first, what you probably want is a JSONLINES file, not a JSON file. Each line is a lone JSON object, with no newlines. That way, when you append, you don't need to read the whole damn file first.

Still, I'm curious why the deserilizer isn't smart enough to deal with a single item although I'm guessing it has to do with some of the List<Class> voodoo.
Because what you're asking it to do is nonsense. A List<ThatHappensToContainAFoo> is not the same object as a Foo, but you're expecting the JSON parser to read your mind and do the conversion.
 

sryan2k1

Ars Legatus Legionis
46,877
Subscriptor++
First things first, what you probably want is a JSONLINES file, not a JSON file. Each line is a lone JSON object, with no newlines. That way, when you append, you don't need to read the whole damn file first.

I'm pretty printing the JSON because we want these to be human readable (occasionally). The events are 5 items and typically there will be 1-10 per day max, only if the POST fails, so rewriting the file each time isn't a big deal.

Because what you're asking it to do is nonsense. A List<ThatHappensToContainAFoo> is not the same object as a Foo, but you're expecting the JSON parser to read your mind and do the conversion.

Powershell's "ConvertFrom-Json" correctly handles it in both cases, dumping either 1 or 2+ items into an array, which I understand is more loosely typed.
 

hanser

Ars Legatus Legionis
43,847
Subscriptor++
There's a type system in C#. You're trying to ignore it. :)


Pattern-wise, I usually go with a collection when the domain indicates that the collection could contain more than one Foo in the future, even if there are no use cases where that's the case today. I don't consider it over-engineering because the LOE required to go with a collection upfront is the time it takes you to type the extra characters, so it's not much of an extra burden. Maybe in other languages, that's less true.
 

minnmass

Ars Tribunus Militum
2,087
Subscriptor
Powershell's "ConvertFrom-Json" correctly handles it in both cases, dumping either 1 or 2+ items into an array, which I understand is more loosely typed.

It depends on your definition of "correct".

C#'s processing is correct: C# is a strongly-typed language and the file didn't contain the expected contents: a valid JSON representation of a List<Foo>. The JSON parser correctly reported that error condition via an exception, as per its contract.

PowerShell's processing is correct: PowerShell is a strongly-ish-typed language that (at least in this case) explicitly and intentionally ignores the difference between "a foo" and "a collection of foos". More specifically, ConvertFrom-Json doesn't ask for a specific type into which to deserialize the JSON document but infers it from the text itself; it can't say "this JSON document is invalid: it's a single foo rather than a collection of them" because it hasn't been told what to expect.