作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何为自定义 JsonConverter 设置 FloatParseHandling.Decimal?
我们有一个结构体 DecimalDbValue,它在内部只保存一个我想对其所有类型进行反/序列化的十进制字段。
它使用魔数(Magic Number) (decimal.MinValue) 来指示“空”值。它是在具有可为空值类型的 .net 2.0 之前创建的!
这是我们结构的精简版本:
[Serializable]
[JsonConverter(typeof(DecimalDbValueJsonConverter))]
public struct DecimalDbValue : ISerializable
{
private readonly Decimal _decValue;
public DecimalDbValue(
decimal init)
{
_decValue = init;
}
[JsonConstructor]
public DecimalDbValue(
decimal? init)
{
if (init.HasValue)
_decValue = init.Value;
else
_decValue = decimal.MinValue;
}
private DecimalDbValue(
SerializationInfo objSerializationInfo,
StreamingContext objStreamingContext)
{
_decValue = objSerializationInfo.GetDecimal("value");
}
public bool IsNotNull
{
get
{
return !IsNull;
}
}
public bool IsNull
{
get
{
return _decValue.Equals(Decimal.MinValue);
}
}
public Decimal Value
{
get
{
return _decValue;
}
}
public void GetObjectData(
SerializationInfo info,
StreamingContext context)
{
info.AddValue("value", _decValue);
}
}
class DecimalDbValueJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(DecimalDbValue) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var value = reader.Value == null ? (decimal?)null : Convert.ToDecimal(reader.Value);
return new DecimalDbValue(value);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dbValue = (DecimalDbValue)value;
if (dbValue.IsNull)
writer.WriteNull();
else
writer.WriteValue(dbValue.Value);
}
}
[JsonConverter(typeof(DecimalDbValueJsonConverter))]
在 DecimalDbValue 结构上
[Test]
public void TestMaxDecimalDbValue()
{
var s = new DecimalDbValue(decimal.MaxValue);
var json = JsonConvert.SerializeObject(s, Formatting.Indented);
var x = JsonConvert.DeserializeObject<DecimalDbValue>(json);
Assert.AreEqual(s, x);
}
System.OverflowException : Value was either too large or too small for a Decimal.
FloatParseHandling.Decimal
对于 JsonConverter?如何使其适用于
MaxValue
还有?有没有其他办法?
decimal?
一样序列化/反序列化(可为空的十进制)
最佳答案
这似乎是不可能的。
因此我完全删除了 JsonConverter。
在结构上设置此属性:
[JsonObject(MemberSerialization.OptIn)]
[JsonConstructor]
public DecimalDbValue(
decimal? init) //IMPORTANT: if you change the name of init - rename the JsonProperty below too - you might break all existing json out there thou!
[JsonProperty("init")]
public Decimal Value
{
get
{
return _decValue;
}
}
{
"init": 79228162514264337593543950335.0
}
关于c# - 如何为自定义 JsonConverter 设置 FloatParseHandling.Decimal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59625363/
我是一名优秀的程序员,十分优秀!