我有一個具有 type 屬性的類Tuple<int, int>,該類被分配了默認值(-1, -1)。我還有一個 json 字符串,表示該類的對象,并為元組屬性分配了非默認值。當我嘗試使用 Json.NET 反序列化 json 字符串時,返回的對象的屬性具有默認值。如果我刪除類定義中的屬性默認分配,則 json 字符串將被正確反序列化。這似乎只發生在元組類型的屬性上。例如,我嘗試使用字符串屬性,反序列化非默認值沒有任何問題。如何正確反序列化具有默認值的元組屬性?這是我應該在 Json.NET 上報告的錯誤嗎?using System;using Newtonsoft.Json;namespace ConsoleApp1{ public class MyClass { public Tuple<int, int> TuplePropertyWithDefault { get; set; } = new Tuple<int, int>(-1, -1); public string StringPropertyWithDefault { get; set; } = ""; public Tuple<int, int> TuplePropertyWithoutDefault { get; set; } public string StringPropertyWithoutDefault { get; set; } public override string ToString() { return $"TuplePropertyWithDefault = {TuplePropertyWithDefault}\n" + $"TuplePropertyWithoutDefault = {TuplePropertyWithoutDefault}\n" + $"StringPropertyWithDefault = {StringPropertyWithDefault}\n" + $"StringPropertyWithoutDefault = {StringPropertyWithoutDefault}\n"; } } class Program { static void Main(string[] args) { var expected = new MyClass(); expected.TuplePropertyWithDefault = new Tuple<int, int> (0, 0); expected.TuplePropertyWithoutDefault = new Tuple<int, int> (0, 0); expected.StringPropertyWithDefault = "test"; expected.StringPropertyWithoutDefault = "test"; var jsonString = JsonConvert.SerializeObject(expected).ToString(); var deserialized = JsonConvert.DeserializeObject<MyClass>(jsonString); Console.WriteLine("Expected:"); Console.WriteLine(expected); Console.WriteLine("Deserialized:"); Console.WriteLine(deserialized); Console.ReadLine(); } }}以 .Net Framework 4.7.2 為目標,并使用 Newtonsoft.Json 版本 12.0.2。
1 回答

慕村225694
TA貢獻1880條經驗 獲得超4個贊
我懷疑這是因為 Json.NET 期望 POCO 子對象是標準的可變類,但該Tuple<...>
系列是不可變的。
坦率地說,由于命名的原因,無論如何Tuple<...>
這里都是一個糟糕的選擇,因此:您可能可以通過花費大量時間為 Json.NET 編寫自定義代碼來配置自己以擺脫這種情況,但是......僅僅聲明似乎更務實和明智您自己的具有合適屬性的 POCO。
附帶說明:值元組是可變的,并且似乎以您期望的方式工作,但是:出于相同的命名原因以及其他原因,我認為它們不會在這里做出好的選擇。
- 1 回答
- 0 關注
- 144 瀏覽
添加回答
舉報
0/150
提交
取消