像这样的东西怎么样:
class BoolStringConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (typeof(string) == objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
string str = token.Value<string>();
if (string.Equals("true", str, StringComparison.OrdinalIgnoreCase) ||
string.Equals("false", str, StringComparison.OrdinalIgnoreCase))
{
str = str.ToLower();
}
return str;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
演示:
class Program
{
static void Main(string[] args)
{
string json = @"
{
""Bool1"": true,
""Bool2"": ""TRUE"",
""Bool3"": false,
""Bool4"": ""FALSE"",
""Other"": ""Say It Isn't True!""
}";
Foo foo = JsonConvert.DeserializeObject<Foo>(json, new BoolStringConverter());
Console.WriteLine("Bool1: " + foo.Bool1);
Console.WriteLine("Bool2: " + foo.Bool2);
Console.WriteLine("Bool3: " + foo.Bool3);
Console.WriteLine("Bool4: " + foo.Bool4);
Console.WriteLine("Other: " + foo.Other);
}
}
class Foo
{
public string Bool1 { get; set; }
public string Bool2 { get; set; }
public string Bool3 { get; set; }
public string Bool4 { get; set; }
public string Other { get; set; }
}
输出:
Bool1: true
Bool2: true
Bool3: false
Bool4: false
Other: Say It Isn't True!