I'd like to convert an object into json and then parse the json back to the original object. The difficulty is there are a list of GENERIC objects as a member. I can convert object into json but don't know how to parse the json back to object with generic type. Does anyone know how to do it?
The json library I use is Newtonsoft.Json.
Any help is appreciated.
public class TestGeneric2
{
public void test()
{
MyClass myObj = new MyClass();
List<Element<IMyInterface>> list = new List<Element<IMyInterface>>();
list.Add(new Element<IMyInterface>(new C1("bbb")));
list.Add(new Element<IMyInterface>(new C2(5.43)));
myObj.list = list;
// convert to json
var json = JsonConvert.SerializeObject(myObj);
Console.WriteLine(json);
// parse json
parseJson(json);
}
public void parseJson(string json)
{
Console.WriteLine("parsing...");
// How to parse the json back to MyClass?
}
}
interface IMyInterface{}
class C1 : IMyInterface
{
public string StrValue;
public C1(string s)
{
StrValue = s;
}
}
class C2 : IMyInterface
{
public double DoubleValue; // different member type than C1
public C2(double v)
{
DoubleValue = v;
}
}
class Element<T> where T : IMyInterface
{
public T Value;
public Element(T value)
{
Value = value;
}
}
class MyClass
{
public List<Element<IMyInterface>> list;
}
The statement "Console.WriteLine(json);" outputs {"list":[{"Value":{"StrValue":"bbb"}},{"Value":{"DoubleValue":5.43}}]} I don't know how to parse it because the two elements in the list have different types.