Reputation: 895
I'm having trouble finishing this method. How can I pass class as parameter and return the same class? This is the scenario I've met
Class A
{
...
}
Class C
{
....
}
Class B
{
A a = getJSONClass(String jsonString, classA?);
C c = getJSONClass(String jsonString, classC?);
public (class?) getJSONClass(String jsonString, class?)
{
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
DataContractJsonSerializer ser = new DataContractJsonSerializer(class?.type);
return ser.ReadObject(memoryStream) as class?;
}
}
Any help??
Upvotes: 0
Views: 135
Reputation: 152491
Well syntactically you'd use generics:
public T getJSONClass<T>(String jsonString) where T : class
{
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
return ser.ReadObject(memoryStream) as T;
}
usage:
A a = getJSONClass<A>(String jsonString);
C c = getJSONClass<C>(String jsonString);
Upvotes: 3
Reputation: 742
Can't you do something like:
Class A
{
...
}
Class C
{
....
}
Class B
{
A a = (A)getJSONClass(String jsonString, typeof(A));
C c = (C)getJSONClass(String jsonString, typeof(C));
public object getJSONClass(String jsonString, Type type)
{
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
DataContractJsonSerializer ser = new DataContractJsonSerializer(type);
return ser.ReadObject(memoryStream);
}
}
Upvotes: 1
Reputation: 398
Use generics:
public T GetDeserializedObject<T>(string jsonString) where T: class
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
return serializer.ReadObject(stream) as T;
}
}
Upvotes: 1