locked
can i convert a string to a type? RRS feed

  • Question

  • User1034446946 posted

    HI

    I have a string which has the name of a class in it

    var myClass = "ModalA";

    public class ModelA
    {
    public bool someVariable {get;set;}
    }

    now i want to serialize a json string to a model

    var myModel = JsonConvert.Deserialize<myClass>(someJsonVariable)

    any thoughts would be appriciated

    Sunday, February 2, 2020 4:41 PM

Answers

  • User-474980206 posted

    Try:

    var type = Type.GetType(myClass); // convert string to type
    var myModel = JsonConvert.DeserializeObject(someJsonVariable, type);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, February 2, 2020 6:22 PM

All replies

  • User1120430333 posted

    IMO. what you want can't be done.

    Sunday, February 2, 2020 5:47 PM
  • User-474980206 posted

    Try:

    var type = Type.GetType(myClass); // convert string to type
    var myModel = JsonConvert.DeserializeObject(someJsonVariable, type);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, February 2, 2020 6:22 PM
  • User1034446946 posted

    thanks

    Sunday, February 2, 2020 9:15 PM