System.Text.Json – Deserialize nested object as string

Found a right way how to correctly read the nested JSON object inside the JsonConverter. The complete solution is the following: public class SomeModel { public int Id { get; set; } public string Name { get; set; } [JsonConverter(typeof(InfoToStringConverter))] public string Info { get; set; } } public class InfoToStringConverter : JsonConverter<string> { public … Read more

Parsing a JSON file with .NET core 3.0/System.text.Json

Update 2019-10-13: Rewritten the Utf8JsonStreamReader to use ReadOnlySequences internally, added wrapper for JsonSerializer.Deserialize method. I have created a wrapper around Utf8JsonReader for exactly this purpose: public ref struct Utf8JsonStreamReader { private readonly Stream _stream; private readonly int _bufferSize; private SequenceSegment? _firstSegment; private int _firstSegmentStartIndex; private SequenceSegment? _lastSegment; private int _lastSegmentEndIndex; private Utf8JsonReader _jsonReader; private bool … Read more

C# – Deserializing nested json to nested Dictionary

In order to deserialize free-form JSON into .Net primitive types instead of JsonElement objects, you will need to write a custom JsonConverter, as no such functionality is provided by System.Text.Json out of the box. One such converter is the following: public class ObjectAsPrimitiveConverter : JsonConverter<object> { FloatFormat FloatFormat { get; init; } UnknownNumberFormat UnknownNumberFormat { … Read more

Equivalent of JObject in System.Text.Json

As of Nov 2021, .NET 6 introduces the System.Text.Json.Nodes namespace which: Provides types for handling an in-memory writeable document object model (DOM) for random access of the JSON elements within a structured view of the data The four new types are JsonArray, JsonObject, JsonNode and JsonValue. The closest type to JObject is JsonObject which offers … Read more

How to use default serialization in a custom System.Text.Json JsonConverter?

As explained in the docs, converters are chosen with the following precedence: [JsonConverter] applied to a property. A converter added to the Converters collection. [JsonConverter] applied to a custom value type or POCO. Each case needs to be dealt with separately. If you have [JsonConverter] applied to a property., then simply calling JsonSerializer.Serialize(writer, person, options); … Read more

ASP.NET Core 3.0 System.Text.Json Camel Case Serialization

AddJsonOptions() would config System.Text.Json only for MVC. If you want to use JsonSerializer in your own code you should pass the config to it. var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; var json = “{\”firstname\”:\”John\”,\”lastname\”:\”Smith\”}”; var person = JsonSerializer.Parse<Person>(json, options);