I created Boolean converter expecting it would be used automatically on the property IsComplete, but get an error in cURL. What am I doing wrong?
Error
$ 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."]}}
Converter
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());
}
}
Attributes
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
You can try to register your custom converter on IsComplete
property of your TodoItem
class.
[JsonConverter(typeof(BooleanConverter))]
public bool IsComplete { get; set; }
For more information about "register a custom converter ", please check: