0

Environment

  • .net 7
  • Using Both System.Text.Json
  • Also NewtonSoft.Json ( 13.0.2)

Example code

string str = @"{
    ""DateTimeNull"":""""
}";
try
{
    var t = System.Text.Json.JsonSerializer.Deserialize<Test>(str);
}
catch (JsonException ex) 
{
    Console.WriteLine(new { Field = ex.Path , Message = ex.Message });
}

try
{
    var t = Newtonsoft.Json.JsonConvert.DeserializeObject<Test>(str);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

public class Test
{
    public DateTime? DateTimeNull { get; set; }
}

In above System.Text.Json Deserlizer throw exception but newtonsoft.json line is not throwing any exception. It is converting empty value to null but I want it should thow error and due to limitation I can not move to System.Text.Json as of now.

  • Payload ( This is i already set in str)
  • Sample one
@"{
    ""DateTimeNull"":""""
}";

Expected result: Throw error and should not convert to null.

  • Sample two.
@"{
    ""DateTimeNull"": null
}";

Expected result: Should not throw error and it is null value and destination type is null.

dotnetstep
  • 17,065
  • 5
  • 54
  • 72

1 Answers1

1

I usually recommend to use a JsonConstructor:

var json = @"{
    ""DateTimeNull"":""""
}";

Test test = JsonConvert.DeserializeObject<Test>(json);

public class Test
{
    public DateTime? DateTimeNull { get; set; }
    
    [Newtonsoft.Json.JsonConstructor]
    public Test(JToken DateTimeNull)
    {
        if (DateTimeNull.Type == JTokenType.Null) this.DateTimeNull = null;
        else if ((string)DateTimeNull == string.Empty)
            throw new JsonException("DateTimeNull property should not be an empty string");
        else this.DateTimeNull = DateTimeNull.ToObject<DateTime>();
    }
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Serge
  • 40,935
  • 4
  • 18
  • 45