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

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

我可以使用 System.Text.Json 通過私有構造函數反序列化 Json 嗎?

我可以使用 System.Text.Json 通過私有構造函數反序列化 Json 嗎?

PHP
揚帆大魚 2024-01-20 16:05:07
想知道是否可以擁有私有構造函數并使用新的 System.Text.Json 序列化器。public class MyModel{    public string Name { get; set; }    public string Data { get; set; }    private MyModel()     {        // use me for when deserializing    }    public MyModel(string name, string data)    {        Name = name;        Data = data;    }}簡單的往返。var model = new MyModel("doo", "doo");var json = JsonSerializer.Serialize(model, new JsonSerializerOptions{    WriteIndented = true});// no to go because of there is no parameterless constructor defined for this object.var rehydrated = JsonSerializer.Deserialize<MyModel>(json);
查看完整描述

3 回答

?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

.NET 8.0 中的更新

只需添加JsonConstructorAttribute到私有構造函數中,如下所示:


public class Employee

{

   [JsonConstructor] // This will work from .NET 8.0

   private Employee()

   {

   }


   private Employee(int id, string name)

   {

     Id = id;

     Name = name;

   }


   [JsonInclude]

   public int Id { get; private set; }


   [JsonInclude]

   public string Name { get; private set; }


   public static Employee Create(int id, string name)

   {

     Employee employee = new Employee(id, name);

     return employee;

   }

}


.NET 7.0 中的更新

從 .NET 7.0 開始,可以通過編寫自己的 ContractResolver 使用私有無參數構造函數來完成反序列化,如下所示:


public class PrivateConstructorContractResolver : DefaultJsonTypeInfoResolver

{

   public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)

   {

       JsonTypeInfo jsonTypeInfo = base.GetTypeInfo(type, options);


       if (jsonTypeInfo.Kind == JsonTypeInfoKind.Object && jsonTypeInfo.CreateObject is null)

       {

         if (jsonTypeInfo.Type.GetConstructors(BindingFlags.Public | BindingFlags.Instance).Length == 0)

         {

            // The type doesn't have public constructors

            jsonTypeInfo.CreateObject = () => 

                Activator.CreateInstance(jsonTypeInfo.Type, true);

         }

       }


      return jsonTypeInfo;

   }

}

使用方法如下:


private static void Main(string[] args)

{

    JsonSerializerOptions options = new JsonSerializerOptions

    {

       TypeInfoResolver = new PrivateConstructorContractResolver()

    };


    Employee employee = Employee.Create(1, "Tanvir");

    string jsonString = JsonSerializer.Serialize(employee);

    Employee employee1 = JsonSerializer.Deserialize<Employee>(jsonString , options);

}


public class Employee

{

   private Employee()

   {

   }


   private Employee(int id, string name)

   {

     Id = id;

     Name = name;

   }


   [JsonInclude]

   public int Id { get; private set; }


   [JsonInclude]

   public string Name { get; private set; }


   public static Employee Create(int id, string name)

   {

     Employee employee = new Employee(id, name);

     return employee;

   }

}


查看完整回答
反對 回復 2024-01-20
?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

答案似乎是“否”,或者至少是“還沒有”。

這是[System.Text.Json]?v1的 System.Text.Json 序列化程序的已知限制。我們計劃將來支持這一點。?-阿松汗

您可以為此編寫一個自定義轉換器...對于[ASP.NET Core]?3.0 版本,沒有計劃在反序列化期間調用非默認構造函數的額外支持。這必須由定制轉換器來完成。——史蒂夫哈特

鏈接的自定義轉換器選項將允許您使用您擁有的任何 API 來構建對象,但與 Newtonsoft.Json 或實體框架通過擺弄反射和私有構造函數可以完成的操作不同,所以可能不是你在尋找什么。


查看完整回答
反對 回復 2024-01-20
?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

您需要使用 JsonConstructor 屬性。

查看完整回答
反對 回復 2024-01-20
  • 3 回答
  • 0 關注
  • 185 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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