JSON 值未在 cURL 中转换为 System.Boolean

JSON value not converted to System.Boolean in cURL

我创建了布尔转换器,希望它能在 属性 IsComplete 上自动使用,但在 cURL 中出现错误。我做错了什么?

错误

$ curl -k -X PUT -H "Content-Type: application/json" -d "{\"name\": \"momo\", \"isComplete\":\"true\"}" https://localhost:44358/api/TodoItems/PutItem?id=2
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|f2fadf22-471bc26be11d1bad.","errors":{"$.isComplete":["The JSON value could not be converted to System.Boolean. Path: $.isComplete | LineNumber: 0 | BytePositionInLine: 36."]}}

转换器

namespace System.Text.Json.Serialization
{
    public class BooleanConverter : JsonConverter<bool>
    {

        public override bool Read(
            ref Utf8JsonReader reader,
            Type typeToConvert,
            JsonSerializerOptions options) =>
            bool.Parse(reader.GetString());

        public override void Write(
            Utf8JsonWriter writer,
            bool b,
            JsonSerializerOptions options) =>
            writer.WriteStringValue(b.ToString());
    }
}

属性

namespace TodoApi.Models
{
    public class TodoItem
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }
}

I created Boolean converter expecting it would be used automatically on the property IsComplete

您可以尝试在 TodoItem class 的 IsComplete 属性 上注册您的自定义转换器。

[JsonConverter(typeof(BooleanConverter))]
public bool IsComplete { get; set; }

更多关于“注册自定义转换器”的信息,请查看:

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to#register-a-custom-converter