StringBoolConverter Convert string to bool

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class StringBoolConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(((bool)value) ? "TRUE" : "FALSE");
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return reader.Value.ToString() == "TRUE";
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(bool);
        }
    }
c#

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
using Newtonsoft.Json;

public class Test
{
    [JsonConverter(typeof(StringBoolConverter))]
    public bool A {get;set;}
}

var test = new Test(){A=true};
JsonConvert.SerializeObject(test);
=>>  {"A":"TRUE"}

//this can be supported default
JsonConvert.DeserializeObject(
         @"{""A"":""TRUE""}"
        );
c#
记录平时瞎折腾遇到的各种问题, 方便查找
使用 Hugo 构建
主题 Stack 3.29.0Jimmy 设计