Start Debugging
2023-09-03 Actualizado 2023-11-05 dotnetdotnet-8 Edit on GitHub

.NET 8 deserializar en propiedades de solo lectura

Aprende a deserializar JSON en propiedades de solo lectura sin setter en .NET 8 usando JsonObjectCreationHandling o JsonSerializerOptions.

A partir de .NET 8 puedes deserializar en propiedades que no tienen accesor set. Puedes activar este comportamiento mediante JsonSerializerOptions o por tipo, usando el atributo JsonObjectCreationHandling.

Usando el atributo JsonObjectCreationHandling

Puedes anotar tu tipo con el atributo System.Text.Json.Serialization.JsonObjectCreationHandling, pasando tu opción como parámetro.

[JsonObjectCreationHandling(JsonObjectCreationHandling.Populate)]
public class Foo
{
     public int Bar { get; }
}

Usando JsonSerializerOptions

Puedes establecer la propiedad JsonSerializerOptions.PreferredObjectCreationHandling en Populate y pasarla al método Deserialize.

new JsonSerializerOptions 
{ 
    PreferredObjectCreationHandling = JsonObjectCreationHandling.Populate
};

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.

< Volver