简体   繁体   中英

How do I retrieve values in an Object and covert them into different variable types?

I'm retrieving some values through Json and I convert them into object. Next I want to pass them in to the database through DBAccess.cs script. This is done through a MVC. All I wanted is to get the values stored in that object

Here's the controller.cs:

public IHttpActionResult PostRegister([FromBody] dynamic register)
{
    try
    {
        Newtonsoft.Json.Linq.JObject employeeRes = (Newtonsoft.Json.Linq.JObject)register.employeedetails;

        var employee = employeeRes.ToObject<Employee>();

        var inserted_id = uMgt.insertRegDetail(employeeRes);
        int nid = (int)inserted_id;

        return Ok("success");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return Ok("fail");
    }
}

Here's the userManagement.cs

public int insertRegDetail(Employee emp)
{
            try 
            {
                var new_id = db.PassRegistraiondetails("new_insert_detail", emp.Fname, emp.Lname, Convert.ToDateTime(emp.Date_of_Birth), emp.Nic, emp.Gender, emp.Email, emp.Mobile_no, Convert.ToInt32(emp.Department_name), emp.Designation, Convert.ToDateTime(emp.Date_of_join));

                return (new_id);
            }
            catch(Exception ex)
            {
              Console.WriteLine(ex.Message);
              return (0);
            }
}

And finally the DBAccess.cs

public int PassRegistraiondetails(string spName, string FName, string LName, DateTime dob, string nic, string Gender, string email, int tel, int id, string Designation, DateTime doj)
{
            try
            {
                SqlCommand cmd = new SqlCommand();
                SqlParameter param;
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = spName;

                param = new SqlParameter("@fname", SqlDbType.NChar);
                param.Value = FName;
                param.IsNullable = true;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@lname", SqlDbType.NChar);
                param.Value = LName;
                param.IsNullable = true;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@DOB", SqlDbType.Date);
                param.Value = dob;
                param.IsNullable = true;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@gender", SqlDbType.NChar);
                param.Value = Gender;
                param.IsNullable = true;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@email", SqlDbType.NChar);
                param.Value = email;
                param.IsNullable = true;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@mobile_no", SqlDbType.Int);
                param.Value = tel;
                param.IsNullable = true;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@designation", SqlDbType.VarChar);
                param.Value = Designation;
                param.IsNullable = true;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@date_of_join", SqlDbType.Date);
                param.Value = doj;
                param.IsNullable = true;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@nic", SqlDbType.NChar);
                param.Value = nic;
                param.IsNullable = true;
                cmd.Parameters.Add(param);

                param = new SqlParameter("@dept_id", SqlDbType.Int);
                param.Value = id;
                param.IsNullable = false;
                cmd.Parameters.Add(param);

                cmd.Parameters.Add("@new_id", SqlDbType.Int).Direction = ParameterDirection.Output;

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    this.OpenConnection();
                    cmd.ExecuteNonQuery();
                    int ID = Convert.ToInt32(cmd.Parameters["@new_id"].Value);
                    this.CloseConnection();
                    return ID;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return (0);
            }
}

The error I get now is that:

Cannot convert Newtonsoft.Json.Linq.JObject to Doman.Employee

<-- Here domain is a base class

How do I resolve this. Hep would be great appreciated

Here's my JSON data

{ "employeedetails": 
     {"Fname":"awad","Lname":"adadad","Date_of_Birth":"09/13/2016",
      "Nic":"asdasdasd","Gender":"Male",
      "Email":"asQsa@c","Mobile_no":"1234234234",
      "Designation":"asdasd","Date_of_join":"09/27/2016",
      "Department_name":"1"
     }
}

Here's my Employee.cs

namespace Efutures.HR.LeaveManagement.Domain
{
    public class Employee
    {
        public string Empid { get; set; }
        public string Fname { get; set; }
        public string Lname { get; set; }
        public string Date_of_Birth { get; set; }
        public string Gender { get; set; }
        public string Email { get; set; }
        public int Mobile_no { get; set; }
        public string Designation { get; set; }
        public string Date_of_join { get; set; }
        public string Nic { get; set; }
        public string Department_name { get; set; }
    }
}

Ashane Alvis, If you see the JSON you are getting it has a property called employeedetails in which you have the object containing the employee information.

So you need a class let's say Employee having a property called employeedetails which is of type let's say EmployeeDetails that is having the rest of the properties in the main property employeedetails in the given JSON.

Check the below code snippet it will convert the JSON you've provided into an employee object.

namespace TestProject
{
    using Newtonsoft.Json;
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            var json = "{\"employeedetails\":{\"Fname\":\"awad\",\"Lname\":\"adadad\",\"Date_of_Birth\":\"09/13/2016\",\"Nic\":\"asdasdasd\",\"Gender\":\"Male\",\"Email\":\"asQsa @c\",\"Mobile_no\":\"1234234234\",\"Designation\":\"asdasd\",\"Date_of_join\":\"09/27/2016\",\"Department_name\":\"1\"}}";
            var employee = JsonConvert.DeserializeObject(json, typeof(Employee));

            Console.ReadKey();
        }
    }

    public class Employee
    {
        public EmployeeDetails employeedetails { get; set; }
    }

    public class EmployeeDetails
    {
        public string Empid { get; set; }

        public string Fname { get; set; }

        public string Lname { get; set; }

        public string Date_of_Birth { get; set; }

        public string Gender { get; set; }

        public string Email { get; set; }

        public int Mobile_no { get; set; }

        public string Designation { get; set; }

        public string Date_of_join { get; set; }

        public string Nic { get; set; }

        public string Department_name { get; set; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM