Reputation: 145
I am trying to use Newtonsoft Json in my project. What I want to do is like below.
public class Subscribe<T> : BaseSubscribe where T : Message, new() // A class
message.body = JsonConvert.DeserializeObject <T.body>(receiveMessage); // In a class member functiton
I got an error. T is a generic variable so I can not initialize. Is there any ways to use json converter on generic variable? thanks.
Upvotes: 0
Views: 228
Reputation: 3764
If you want to be able to deserialise generic types using JsonConvert then you will need to help the deserialiser by supplying the concrete type name in your json. This is done using the TypeNameHandling flag on the JsonSerializerSettings object. Example below.
[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);
}
}
Upvotes: 1
Reputation: 1611
try this:
var message = JsonConvert.DeserializeObject<T>(receiveMessage);
var messageBody = message.body;
But please, share more of your code and the error.
Upvotes: 2