簡體   English   中英

如何在 C# 中對泛型變量使用 Json 反序列化

[英]How to use Json deserialization on generic variable in c#

我想在我的項目中使用 Newtonsoft Json。 我想做的是如下。

public class Subscribe<T> : BaseSubscribe where T : Message, new() // A class 

message.body = JsonConvert.DeserializeObject <T.body>(receiveMessage); // In a class member functiton

我有一個錯誤。 T 是一個通用變量,所以我無法初始化。 有什么方法可以在通用變量上使用 json 轉換器嗎? 謝謝。

嘗試這個:

var message = JsonConvert.DeserializeObject<T>(receiveMessage);
var messageBody = message.body;

但是,請分享更多您的代碼和錯誤。

如果您希望能夠使用 JsonConvert 反序列化泛型類型,那么您需要通過在 json 中提供具體類型名稱來幫助反序列化器。 這是使用 JsonSerializerSettings 對象上的 TypeNameHandling 標志完成的。 下面舉例。

    [TestFixture]
    public class GenericJsonConvertFixture
    {
    public abstract class Employee
    {
        public string Name { get; set; }
    }

    public class Manager : Employee
    {
    }

    public class Subscribe<T> where T : Employee
    {
        public T Employee { get; set; }
    }

    [Test]
    public async Task TestDeserialisingGenericTypes()
    {
        var sub = new Subscribe<Employee>()
        {
            Employee = new Manager() { Name = "Elon" }
        };

        var json = JsonConvert.SerializeObject(sub, new JsonSerializerSettings()
        {
            TypeNameHandling = TypeNameHandling.Objects
        });

        var newSub = JsonConvert.DeserializeObject(json, new JsonSerializerSettings()
        {
            TypeNameHandling = TypeNameHandling.Objects
        });

        Assert.That(newSub is Subscribe<Employee>);
        Assert.That(((Subscribe<Employee>)newSub).Employee is Manager);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM