Support Nullable Types

Abierto
#3 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
25/100
Tipo de issue
Nueva funcionalidad
Claridad
Necesita aclaración
Estado de actividad
Estancado
Stack tecnológico
csharp

Línea de trabajo

Comienza con DevBetter.JsonExtensions.Converters.MissingMemberErrorConverter y el código fuente que convierte los valores manualmente. Traza cómo Nullable es tratado por el controlador general Error y por los demás controladores. Se considera terminado cuando los valores nullable se deserializan correctamente y la política solicitada para los miembros faltantes está definida para cada controlador, incluido el ejemplo Weather.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Ths is a nice extension for solving the problem, where missing values are silently ignored by default. However, I have some cases where I know beforehand that a value might be missing from the JSON. I represent these in the class I deserialise to as nullable fields.

When I try to deserialise like this:

public class Weather{
    public string description { get; set; }
    public double windSpeed    { get; set; }
    public int? temperature {get;set;}
}

 var deserializeOptions = new JsonSerializerOptions()
          .SetMissingMemberHandling(DevBetter.JsonExtensions.MissingMemberHandling.Error);
        
Weather? result = System.Text.Json.JsonSerializer.Deserialize<Weather>(text, deserializeOptions);

with this JSON:

{
    "temperature": 32,
    "description": "windy. So very windy",
    "windSpeed": 60.05
}

I get

{System.Text.Json.JsonException: The JSON value could not be converted to System.Nullable`1[System.Int32]. Path: $ | .....
 ---> System.InvalidOperationException: The requested operation requires an element of type 'Object', but the target element has type 'Number'.
   at System.Text.Json.JsonElement.EnumerateObject()
   at DevBetter.JsonExtensions.Converters.MissingMemberErrorConverter.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   --- End of inner exception stack trace ---

Looking at the sources, it seems that you're converting types manually, and that the Nullable generic isn't eexplicitly handled yet, so this would be expected, the exception is because it can't construct a system.Nullable from a numeric value yet.

Suggested implementation:
  • If not added to the general Error handler, add a new handler, that behaves like error, except that values that are explicitly nullable in the class do not cause an exception to be thrown if they are missing from the JSON.
  • Add support for nullable types to all handlers, with a policy on how these should be deserialised for that handler.

Thanks!

Lenguaje dominante
C#
Estrellas
4
Forks
1
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de DevBetterCom/DevBetter.JsonExtensions

Todos los issues de DevBetterCom/DevBetter.JsonExtensions

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.