-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Closed
Labels
Description
Description
System.Text.Json is unable to deserialize a very basic struct
Reproduction Steps
using System;
public class Program
{
public enum LengthUnitTypes
{
None,
m,
cm,
mm,
um,
@in,
ft,
km,
mi
}
public struct Length{
public Length()
{
}
public Length(double value, LengthUnitTypes unit)
{
Value = value;
Unit = unit;
}
public double Value { get; set; } = 0;
public LengthUnitTypes Unit { get; set; } = LengthUnitTypes.None;
}
public static void Main()
{
var l = new Length();
var json = System.Text.Json.JsonSerializer.Serialize(l);
Console.WriteLine(json);
l = System.Text.Json.JsonSerializer.Deserialize<Length>(json);
Console.WriteLine("Hello World");
}
}
Result
{"Value":0,"Unit":0}
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at ValueSetter(Object , Double )
at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
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)
at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable`1 actualByteCount)
at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo jsonTypeInfo)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
at Program.Main()
Command terminated by signal 6
See fiddle here https://dotnetfiddle.net/n21G3a
Expected behavior
No exception. And if something is wrong with class/struct declaration, throw a more descriptive exception.
Actual behavior
Throws null reference
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
No response