C sharp and JSON
General notes
Section titled General notes- At least as of mid 2024, the built-in
System.Text.Json
stuff seems pretty powerful. - The official Microsoft documentation is good (although sometimes long).
- Note to self: I worked somewhat extensively with JSON stuff for Skeleseller, so if I’m ever looking for code in the future, check there. To anyone else reading this, the source is closed at the time of writing. 😢
Troubleshooting
Section titled TroubleshootingA custom converter is serializing incorrectly
Section titled A custom converter is serializing incorrectlyThis is the fault of the custom converter I wrote:
Depending on what you want, there are two different fixes:
- If the JSON you want is
"Item": { "id": 1 }
, then surround the call towriter.WriteNumber
withwriter.WriteStartObject();
andwriter.WriteEndObject();
- This also requires a change to the reader (see below); you generally need to loop on
reader.Read()
and check for whenreader.TokenType
isJsonTokenType.StartObject
,JsonTokenType.EndObject
, orJsonTokenType.PropertyName
.
- This also requires a change to the reader (see below); you generally need to loop on
- If the JSON you want is
"Item": 1
, then replacewriter.WriteNumber
withwriter.WriteNumberValue
.
Similarly, if you wanted to write arrays, you need to explicitly call WriteStartArray
and WriteEndArray
.
Example reader change
Section titled Example reader changeThis is kind of ridiculous, but here’s how you would read the { "id": 1 }
object. I didn’t need a loop since I only write one value: