Support Nullable Types

Aberta
#3 0 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
5/5
Tempo estimado
Mais de uma semana
Facilidade para iniciantes
25/100
Tipo de issue
Funcionalidade
Clareza
Precisa de esclarecimento
Status de atividade
Estagnada
Stack de tecnologia
csharp

Direção de pesquisa

Comece com DevBetter.JsonExtensions.Converters.MissingMemberErrorConverter e o código-fonte que converte valores manualmente. Rastreie como Nullable é tratado pelo handler geral Error e pelos outros handlers. Está concluído quando os valores nullable são desserializados corretamente e a política solicitada para membros ausentes está definida para cada handler, incluindo o exemplo Weather.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

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!

Linguagem predominante
C#
Estrelas
4
Forks
1
Métricas de merge de PRs
Nenhum PR com merge em 30d

Preparar o ambiente

Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de DevBetterCom/DevBetter.JsonExtensions

Todas as issues de DevBetterCom/DevBetter.JsonExtensions

Issues semelhantes

Mais issues de C#

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.