我有一个带有对象属性的类,如果我使用该属性的十进制值创建该类并序列化它,该值看起来很好:
var testObject = new TestObject{
TestDecimal = 8801203167395152041.7m
};
var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(testObject);
serialized.Dump(); // returns {"TestDecimal":8801203167395152041.7}
但是,如果我尝试使用 jtoken 反序列化该值,该值将变为科学值并保存为双精度值,以下是整个代码:
void Main()
{
var testObject = new TestObject{
TestDecimal = 8801203167395152041.7m
};
var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(testObject);
serialized.Dump();
TestObject result = JsonConvert.DeserializeObject<TestObject>(serialized, new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new TestDesiralizer() }
});
testObject.TestDecimal.Dump();
result.TestDecimal.Dump();
}
public class TestObject{
public object TestDecimal { get; set; }
}
public class TestDesiralizer : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TestObject);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
serializer.Culture = CultureInfo.InvariantCulture;
reader.Culture = CultureInfo.InvariantCulture;
JToken token = serializer.Deserialize<JToken>(reader);
TestObject obj = token.ToObject<TestObject>();
obj.TestDecimal = decimal.Parse(Convert.ToString(obj.TestDecimal,CultureInfo.InvariantCulture) ?? "",NumberStyles.Any, CultureInfo.InvariantCulture);
return obj;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
这导致:
1) 8801203167395152041,7
2) 8801203167395150000
反序列化json时如何保留十进制值?
DIEA
相关分类