.net C# System.Text.Json 如何将 string类型的“true”转换为布尔值 解决方案
Posted on 2023-12-20 20:40 WebEnh 阅读(121) 评论(0) 编辑 收藏 举报直接上解决方法的代码
先定义一个转换顺,代码如下:
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; } }
希望能帮到您解决问题。
转自:http://Www.CnBlogs.Com/WebEnh/
如果想下次快速找到我,记得点下面的关注哦!
本博客Android APP 下载 |
![]() |
支持我们就给我们点打赏 |
![]() |
支付宝打赏 支付宝扫一扫二维码 |
![]() |
微信打赏 微信扫一扫二维码 |
![]() |
如果想下次快速找到我,记得点下面的关注哦!