我有以下JSON对象:
ALTER TABLE dbo.Poster
ADD CONSTRAINT <Constraint Name Here> UNIQUE(Id_Theater, [Date]);
和以下DTO类:
{
"entity": "Customer",
"id": "XXX",
"isActive": "1",
"createdTime": "2018-01-30T18:56:51+02:00",
"updatedTime": "2019-01-05T02:15:17+02:00",
和反序列化代码:
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>));
属性有问题,因为json对象具有1或0的值,但是我想拥有布尔值。如何编写JsonSerializer来做到这一点?
答案 0 :(得分:1)
Pete在how to get newtonsoft to deserialize yes and no to boolean的非常好的代码
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())