【问题标题】:JSON value not converted to System.Boolean in cURLJSON 值未在 cURL 中转换为 System.Boolean
【发布时间】:2020-10-26 20:11:17
【问题描述】:

我创建了布尔转换器,希望它会在属性 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; }
    }
}

【问题讨论】:

    标签: api asp.net-core jsonconverter


    【解决方案1】:

    我创建了布尔转换器,期望它会在属性 IsComplete 上自动使用

    您可以尝试在 TodoItem 类的 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

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多