我有一个带有对象属性的类,如果我使用该属性的十进制值创建该类并序列化它,该值看起来很好: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,72) 8801203167395150000反序列化json时如何保留十进制值?
1 回答
DIEA
TA贡献1820条经验 获得超2个赞
在反序列化期间设置以下内容似乎可以解决该问题:
reader.FloatParseHandling = FloatParseHandling.Decimal
- 1 回答
- 0 关注
- 139 浏览
添加回答
举报
0/150
提交
取消