Skip to content

System.Text.Json JsonNumberHandling.AllowReadingFromString option don't work on numeric types #169

@bazarniy

Description

@bazarniy

Hello!

There are JsonNumberHandling.AllowReadingFromString. It allow read numbers from json string.
For example this json will be deserealized on raw numeric types (int, long etc) if option set
{"item": "123"}

But in your serializers it bangs in this code:

public override MilestoneId Read(ref global::System.Text.Json.Utf8JsonReader reader, global::System.Type typeToConvert, global::System.Text.Json.JsonSerializerOptions options)
                => new (reader.GetInt64());

Correct way to generate this code is add check for the option and token type. Here is an example:

public override MilestoneId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (options.NumberHandling.HasFlag(JsonNumberHandling.AllowReadingFromString) && reader.TokenType == JsonTokenType.String)
            {
                var str = reader.GetString();

                if (!string.IsNullOrEmpty(str) && MilestoneId.TryParse(str, null, out var val)) return val;
                return default;
            }
            return new MilestoneId(reader.GetInt64());
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions