我有一個(gè)帶有對象屬性的類,如果我使用該屬性的十進(jìn)制值創(chuàng)建該類并序列化它,該值看起來很好:var testObject = new TestObject{ TestDecimal = 8801203167395152041.7m};var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(testObject);serialized.Dump(); // returns {"TestDecimal":8801203167395152041.7}但是,如果我嘗試使用 jtoken 反序列化該值,該值將變?yōu)榭茖W(xué)值并保存為雙精度值,以下是整個(gè)代碼: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(); }}這導(dǎo)致:1) 8801203167395152041,72) 8801203167395150000反序列化json時(shí)如何保留十進(jìn)制值?
1 回答

DIEA
TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超3個(gè)贊
在反序列化期間設(shè)置以下內(nèi)容似乎可以解決該問題:
reader.FloatParseHandling?=?FloatParseHandling.Decimal
- 1 回答
- 0 關(guān)注
- 206 瀏覽
添加回答
舉報(bào)
0/150
提交
取消