dimanche 8 août 2021

How to write a C# Function that returns a class type speficifed as a parameter?

I am trying to write a JSON helper class for a C# MVC app that returns a class instance of the type that is specified as a parameter. The intent of this is to simplify deserializing a JSON into a Model of the right type. the Unfortunately i am running into an error of:

'ModelType' is a variable but used as a type.

Here is the code I am using:


        public ActionResult api_call() {
            // Parse/Map request stream containing a JSON to a C# object
            json_helper _o_json_helper = new json_helper();
            pollread_read_request _request = _o_json_helper.parse_json_to_object(Assembly.GetExecutingAssembly().GetType("pollread_read_request"), Request.InputStream); 
            // Create a business logic instance
            Pollmaker_business_logic _business_logic = new Pollmaker_business_logic();
            // process request using business logic
            List<pollread_read_response> _response = _business_logic.api_call(_request);
            // return result
            return Json(_response, JsonRequestBehavior.AllowGet);
        }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
namespace Umbrella.Abstracts {
    public class json_helper {
        public Object parse_json_to_object(Type ClassModelType, System.IO.Stream InputStream) {
            object _result = Activator.CreateInstance(ClassModelType);
            try {
                string _json_request = "";
                using (System.IO.Stream _oRequestStream = InputStream) {
                    _oRequestStream.Seek(0, System.IO.SeekOrigin.Begin);
                    _json_request = new System.IO.StreamReader(_oRequestStream).ReadToEnd();
                }
                if (!String.IsNullOrEmpty(_json_request)) {
                    _result = Newtonsoft.Json.JsonConvert.DeserializeObject<ClassModelType> (_json_request);
                }
            } catch { }
            return _result;               
        }
        public json_helper() {}
    }
}




Aucun commentaire:

Enregistrer un commentaire