c# - 在 JSON.NET 中反序列化十进制值的自定义规则
问题描述
当我使用JsonConvert.DeserializeObject
将JSON
数据转换为自定义类时遇到问题,只要null
属性值需要decimal
.
我想实现一个自定义规则,该规则仅在我想要时使用——不想要全局设置。在这种特殊情况下,我希望只要属性是十进制类型,null
值就会变为。0
我该如何做到这一点?
解决方案
您可以在要反序列化的类型中使用注释,也可以在反序列化时指定自定义转换器/设置(而不是全局)。我认为,仅处理某些 属性的唯一好方法decimal
是使用注释。
string json = @"{""val"": null}";
public class NoAnnotation {
public decimal val {get; set;}
}
public class WithAnnotation {
[JsonConverter(typeof(CustomDecimalNullConverter))]
public decimal val {get; set;}
}
void Main()
{
// Converting a type that specifies the converter
// with attributes works without additional setup
JsonConvert.DeserializeObject(json, typeof(WithAnnotation));
// Converting a POCO doesn't work without some sort of setup,
// this would throw
// JsonConvert.DeserializeObject(json, typeof(NoAnnotation));
// You can specify which extra converters
// to use for this specific operation.
// Here, the converter will be used
// for all decimal properties
JsonConvert.DeserializeObject(json, typeof(NoAnnotation),
new CustomDecimalNullConverter());
// You can also create custom serializer settings.
// This is a good idea if you need to serialize/deserialize multiple places in your application,
// now you only have one place to configure additional converters
var settings = new JsonSerializerSettings();
settings.Converters.Add(new CustomDecimalNullConverter());
JsonConvert.DeserializeObject(json, typeof(NoAnnotation), settings);
}
// For completeness: A stupid example converter
class CustomDecimalNullConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(decimal);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return 0m;
}
else
{
return Convert.ToDecimal(reader.Value);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue((decimal)value);
}
}
推荐阅读
- python - 在 PyCharm 中找不到 webdriver_manager 模块
- sql - How can I handle unique email violation exception in PostgreSQL?
- python - 使用 Python 在 ::before 标记之后抓取网页内容
- javascript - React - 映射道具值时来自Form的问题定位值
- python - 为什么 x = y += 10 在 python 中无效
- javascript - 在选项卡(面包屑)之后删除 VS 代码文件大纲选项
- c++ - 有人可以解释这个程序吗?我不明白
- for-loop - for循环不执行
- python - 如何分解从 pyautogui.locateCenterOnScreen() 返回的 Point(x=,y=) 值
- r - 正则表达式替换第一个数字后的所有内容,包括用另一个字符串的数字