我有以下JSON对象:
{
"entity": "Customer",
"id": "XXX",
"isActive": "1",
"createdTime": "2018-01-30T18:56:51+02:00",
"updatedTime": "2019-01-05T02:15:17+02:00",
和以下 DTO 类:
public class Customer
{
public string Id { get; set; }
public bool IsActive { get; set; }
public DateTime CreatedTime { get; set; }
public DateTime UpdatedTime { get; set; }
}
和反序列化代码:
var jsonResponse = JObject.Parse(customerString);
JToken array = jsonResponse["response_data"];
List<Customer> result = (List<Customer>)array.ToObject(typeof(List<Customer>));
但是我对IsActive
属性有问题,因为 json 对象有 1 或 0 个值,但我想有布尔值。如何编写 JsonSerializer 来做到这一点?
Pete 非常好的代码,介绍如何让 newtonsoft 将 yes 和 no 反序列化为布尔值
public class JsonBooleanConverter : JsonConverter
{
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var value = reader.Value.ToString().ToLower().Trim();
switch (value)
{
case "true":
case "yes":
case "y":
case "1":
return true;
}
return false;
}
public override bool CanConvert(Type objectType)
{
if (objectType == typeof(Boolean))
{
return true;
}
return false;
}
}
用法:
var myObj = JsonConvert.DeserializeObject<T>(json, new JsonBooleanConverter())