M
M
Mikhail Petrovich2019-03-03 22:58:44
ASP.NET
Mikhail Petrovich, 2019-03-03 22:58:44

How to get the type from a variable?

Hello dear. The essence of the problem is this.
I get JSON in the method "DataCreate(string JsonData, string ObjectName)"
JsonData- the data itself
ObjectName - the name of the object into which this data needs to be deserialized.

var DataObject = oJS.Deserialize<ObjectName>(JsonData);

The string ObjectName contains the name as a string. So I can't use Type not Activator.
You need a specific type. How can I get it.
[HttpPost]
        public JsonResult DataCreate(string JsonData, string ObjectName)
        {
            JavaScriptSerializer oJS = new JavaScriptSerializer();
            var DataObject = oJS.Deserialize<ObjectName>(JsonData);
            return Json(new { Message = "Данные добавлены"}, JsonRequestBehavior.AllowGet);
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
shai_hulud, 2019-03-04
@booleansky

It's just a very big security hole if you allow an object to be mapped to any type. Sooner or later, a type will be selected that will execute / interpret the result on the property set and this hole will be exploited.
It will be safe to map to known types via switch. Or through a pre-prepared dictionary "name / type".

F
freeExec, 2019-03-03
@freeExec

Through reflection

var findClass = System.Reflection.Assembly.GetEntryAssembly().GetTypes().FirstOrDefault(t => t.Name == "FindMe");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question