0

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.

Sean Shi
  • 1,289
  • 2
  • 9
  • 14
  • 2
    Post that information in your question, **not in the comments** – maccettura Mar 05 '18 at 20:14
  • Duplicates: [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182), [How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?](https://stackoverflow.com/q/8030538/3744182), [JSON.NET - how to deserialize collection of interface-instances?](https://stackoverflow.com/q/15880574/3744182) and [Using Json.NET converters to deserialize properties](https://stackoverflow.com/q/2254872/3744182). – dbc Mar 06 '18 at 00:07

0 Answers0