直接上解决方法的代码
先定义一个转换顺,代码如下:
public sealed class AnhBoolConverter : JsonConverter<bool?> { public override bool? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var val = JsonSerializer.Deserialize<string?>(ref reader, options); bool? boolVal = Convert.ToBoolean(val); return boolVal; } public override void Write(Utf8JsonWriter writer, bool? val, JsonSerializerOptions options) => // What do I do here? I want to preserve other options such as options.PropertyNamingPolicy, which are lost by the following call JsonSerializer.Serialize(writer, val); }
再到需要反序列化地实体上添加如下属性(黄色高亮区域):
public class ResponseBase { /// <summary> /// 接口请求结果 true or false /// 示例值:"result": "true" 或 true /// </summary> [System.Text.Json.Serialization.JsonConverter(typeof(AnhBoolConverter))] public bool? result { set; get; } /// <summary> /// 系统返回结果描述 /// 示例值:接口调用成功 /// </summary> public string? msg { set; get; } /// <summary> /// 错误码 /// </summary> public string? errCode { get; set; } }
希望能帮到您解决问题。
标签:string,val,C#,Text,public,bool,true,options From: https://www.cnblogs.com/webenh/p/17917529.html