0

I have multiple classes extended from an interface and I have a json editor to edit each of those classes that I have in a List, "I" being my interface

So let's say I have the variable of the current class which properties have been edited

I now have the new Json that contains the new values

How do I deserialize the new json according to the current class being edited?

I have access to the class name if that can help but I can't find a way to do

I have tried .GetType() for the current selected Class : IRule and reflector


class RuleOne : IRule
{
    public bool variable{ get; set; }
    public int num;
}

class RuleTwo : IRule
{
    public bool variable{ get; set; }
    public string name;
}

List<IRule> Rules = new List<IRule>;

Rules.Add(new RuleOne());
Rules.Add(new RuleTwo());

string json = JsonConvert.SerializeObject(Rules[0]);

// How do I deserialize the json string into Rules[0] ?

I expect the modified json to be stored in it's original class

yeet
  • 25
  • 3

2 Answers2

0

You need to help serializer to remember the types. Check this thread for more details.

fenixil
  • 2,106
  • 7
  • 13
0
Type type = Type.GetType($"{EditorRule.GetType().Namespace}.{EditorRule.GetType().Name}"); // Can be replaced dynamically
EditorRule = (IRule)JsonConvert.DeserializeObject(JsonText, type);

This worked for me, I didn't know you could also pass a "dynamic" type as an argument to JsonConvert.Deserialize()

yeet
  • 25
  • 3
  • maybe I didn't get your concern correctly, but to use this solution you need to know a type which is in `JsonText` upfront what is not always the case. You need to pass it somehow and there is existing mechanism for that, check my answer. – fenixil Sep 19 '19 at 03:46