Skip to content

Nullable struct converter #30567

@fleed

Description

@fleed

I've written the following converter to consume data from a 3rdparty API:

public class JsonNullableDateTimeOffsetConverter : JsonConverter<DateTimeOffset?>
    {
        public override DateTimeOffset? Read(ref Utf8JsonReader reader, Type typeToConvert,
            JsonSerializerOptions options)
        {
            var value = reader.GetString();
            if (string.IsNullOrEmpty(value))
            {
                return default;
            }

            return DateTimeOffset.ParseExact(reader.GetString(), "yyyy/MM/dd HH:mm:ss zzz",
                CultureInfo.InvariantCulture);
        }

        public override void Write(Utf8JsonWriter writer, DateTimeOffset? value, JsonSerializerOptions options)
        {
            if (!value.HasValue)
            {
                return;
            }
            
            writer.WriteStringValue(value.Value.ToString("yyyy/MM/dd HH:mm:ss zzz"));
        }
    }

The following test

[Fact]
        public void TestNullableDateTimeOffset()
        {
            var s = "{\"nullableValue\":null}";
            var v = JsonSerializer.Deserialize<TestNullable>(s);
        }

throws the exception:
System.FormatException : Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

I have the same exception also when selecting a converter that doesn't match the type.
I think that at least a more meaningful exception should be thrown.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions