Newtonsoft - 将“1”反序列化为条件 bool 属性
Newtonsoft - deserialize “1” as conditional bool property
我有以下 JSON 对象:
{
"entity": "Customer",
"id": "XXX",
"isActive": "1",
"createdTime": "2018-01-30T18:56:51+02:00",
"updatedTime": "2019-01-05T02:15:17+02:00",
和以下 DTO class:
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 在 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())
我有以下 JSON 对象:
{
"entity": "Customer",
"id": "XXX",
"isActive": "1",
"createdTime": "2018-01-30T18:56:51+02:00",
"updatedTime": "2019-01-05T02:15:17+02:00",
和以下 DTO class:
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 在 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())