亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何正確反序列化具有默認分配的元組屬性?

如何正確反序列化具有默認分配的元組屬性?

C#
九州編程 2023-08-27 10:39:24
我有一個具有 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。

附帶說明:值元組是可變的,并且似乎以您期望的方式工作,但是:出于相同的命名原因以及其他原因,我認為它們不會在這里做出好的選擇。


查看完整回答
反對 回復 2023-08-27
  • 1 回答
  • 0 關注
  • 144 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號