locked
web api json format post RRS feed

  • Question

  • User-1396990745 posted

    Hi, I have JSON data in the below format and using the ASP.NET web api post method to load this data into a table. Could you please guide me to deserialize.

    JSON data:

    {
    "data": [
    {
    "Id": "1",
    "Student": "T code",
    "Grade": "Test code"
    }
    ],
    "Token": "",
    "header": [
    "Id",
    "Student",
    "Grade"
    ],
    "Rowcount": 1
    }

    //Model
    
        public class Data
        {
            public string Id { get; set; }
            public string Student { get; set; }
            public string Grade { get; set; }
        }
    
        public class Student
        {
            public IList<Data> data { get; set; }
        }
    
    //Controller	
    
            [HttpPost]
            public IHttpActionResult PostJSON()
            {
    			List<Data> StudentList = JsonConvert.DeserializeObject<List<Data>>(jsonString);
    
    			public static DataTable ToDataTable<T>(this IList<T> data)
    			{
    				PropertyDescriptorCollection props =
    				TypeDescriptor.GetProperties(typeof(T));
    				DataTable table = new DataTable();
    				for(int i = 0 ; i < props.Count ; i++)
    				{
    				PropertyDescriptor prop = props[i];
    				table.Columns.Add(prop.Name, prop.PropertyType);
    				}
    				object[] values = new object[props.Count];
    				foreach (T item in data)
    				{
    				for (int i = 0; i < values.Length; i++)
    				{
    					values[i] = props[i].GetValue(item);
    				}
    				table.Rows.Add(values);
    				}
    				return table;        
    			}
                
            }

    Thanks in advance.

    Thursday, January 25, 2018 7:26 PM

All replies

  • User2103319870 posted

    to load this data into a table

    I guess you are trying to load the data array values in Json to DataTable, if so then you can try with below code

    //Your Json string
                string yourJson = @" {                 ""data"": [
                                    {
                                ""Id"": ""1"",
                                                ""Student"": ""T code"",
                                                ""Grade"": ""Test code""
                                }
                                ],
                                ""Token"": """",
                                ""header"": [
                                ""Id"",
                                ""Student"",
                                ""Grade""
                                ],
                                ""Rowcount"": 1
                                }";
                //Parse the Json
                JObject jObject = JObject.Parse(yourJson);
                //Get the Dataarray as JArray
                JArray dataArray = (JArray)jObject["data"];
                //Convert the array values to datatable
                DataTable dt = (DataTable)JsonConvert.DeserializeObject(dataArray.ToString(), (typeof(DataTable)));

    Above code uses JSON.Net, If you dont have Json.Net in your machine you can get it from Nugget for Json.

    Once you installed then you can use the code given below

    First Ensure that you have added the namespace reference in your page

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;

    Then you can use above code to convert json to datatable

    Thursday, January 25, 2018 8:39 PM
  • User-1396990745 posted

    Hello a2h, Thanks for your response. Instead of hard coding the json string is there a way to assign it as a data stream to the variable string yourJson?

     string yourJson = 

    Regards.

    Thursday, January 25, 2018 9:06 PM
  • User2103319870 posted

    Instead of hard coding the json string is there a way to assign it as a data stream to the variable string yourJson

    I just used it for a demo. You can pass the value directly to variable

    Thursday, January 25, 2018 9:47 PM
  • User-1396990745 posted

    I modified the controller code like below and still run into error.

    //Controller
    
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
        public class UploadController : ApiController
        {
            private IList<string> errors = new List<string>();
            string message = "";
    
            [HttpPost]
            [Route("api/student", Name = "student")]
            public string GetJSonString(jSonStr jsonData)
            {
                if (!string.IsNullOrEmpty(jsonData.jsonStr))
                    return SaveJsontoDB(jsonData.jsonStr);
                else
                    return "{\"success\":false}";
            }
    
            public string GetJSonData(jsonDataCollection jsonData)
            {
                var res = JsonConvert.SerializeObject(jsonData);
                return SaveJsontoDB(res);
            }
            public IHttpActionResult Post()
            {
                errors.Add(SaveJsontoDB(res));
    
                if (errors == null)
                    return Ok("Inserted");
                else
                    return Ok("error message: " + errors);
            }
    
            private string SaveJsontoDB(string oJson)
            {
                const string connectionString = @"Data Source=sqlserver;Initial Catalog=dbname;User Id=user;Password=password;";
    
                try
                {
                    var studentData = JsonSerializer.Deserialize<jsonDataCollection>(oJson);
    
                    foreach (var i in studentData.jsonData)
                    {
                        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
                        {
                            sqlConnection.Open();
    
                            using (SqlCommand cmd = new SqlCommand("INSERT INTO [Student] ([ID], [Student], [Grade]) VALUES (@ID, @Student, @Grade)", sqlConnection))
                            {
                                cmd.Parameters.AddWithValue("@ID", i.ID);
                                cmd.Parameters.AddWithValue("@Student", i.Student);
                                cmd.Parameters.AddWithValue("@Grade", i.Grade);
    
                                cmd.ExecuteNonQuery();
                            }
                        }
                    }
                    return (null);
                }
                catch (Exception ex)
                {
                    message = ex.StackTrace;
                    return (message);
                }
            }
        }
    

    Thank you.

    Friday, January 26, 2018 12:16 AM
  • User283571144 posted

    Hi vscsl,

    I modified the controller code like below and still run into error.

    Welcome to the asp.net forum.

    According to your codes,we couldn't find why you still show the error.

    Could you please post the detail error message, json example and the definition of jsonDataCollection?

    If you could post more details information, it will be more easily for us to reproduce the issue and find the solution.

    Best Regards,

    Brando

    Friday, January 26, 2018 4:19 AM
  • User-1396990745 posted

    Hi Brando thank you for your response and welcoming me to the forum. I am new to web api development and I apologize if I ask any basic questions. Could you please help me understand how to read json data into the json variable dynamically instead hard code it.

    Regards

    Friday, January 26, 2018 7:07 PM
  • User753101303 posted

    Hi,

    In most cases, if you see explicit serialization/deserialization in your code it's likely you are doing it wrong. Web API have already support for deserializing incoming parameters and serializing what you return.

    So I would suggest to use a tool such as http://json2csharp.com/ to generate C# classes (might need to be reworked but still a great help) and then make your API call to accept a suitable object. Web API will create and populate the C# object argument for you.


    Edit: a short and nice example that doesn't have any explicit serialization code is found at :

    http://www.c-sharpcorner.com/UploadFile/dacca2/web-api-with-ajax-understand-post-request-in-web-api/

    Friday, January 26, 2018 7:12 PM
  • User-474980206 posted

    you post back model looks like:

    public class PostBackModel
    {
        public List<Data> data {get; set;}
        public string Token {get; set;}
        public List<string> header {get; set;}
        public int Rowcount {get; set;}
    }
    

    which can easily be mapped to a Student. 

    [HttpPost]
    public IHttpActionResult PostJSON(PostBackModel postdata)
    {
        List<Data> StudentList = postdata.data;
        ....
    }

    Friday, January 26, 2018 9:18 PM
  • User-1396990745 posted

    Hi, I am trying to deserialize the json data to the object/class format and run into cannot convert json collection to string. Please guide me.

    //Model
        public class Student
        {
            public string Id { get; set; }
            public string Student { get; set; }
            public string Grade { get; set; }
        }
    
        public class AllStudents
        {
            public IList<SData> data { get; set; }
        }
    	
    //Controller
    		[HttpPost]
            public IHttpActionResult Post(Student studentjson)
    		{
    			IList<SData> StudentList = studentjson.data;
    			var serializer = new JavaScriptSerializer();
                Student StudentObj = serializer.Deserialize<Student>(studentjson.data.ToString());
    			
                string SQLConnectionString = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;            
                using (SqlConnection conn = new SqlConnection(SQLConnectionString))
                {
                    conn.Open();
                    foreach (var student in StudentObj.data)
                    {
                        if (writetotbl(conn, student))
                        {
                            Console.WriteLine("Success : " + student.Student);
                        }
                        else
                        {
                            Console.WriteLine("Error : " + student.Student);
                        }
                    }
                }			
    		}
    		
    		static bool writetotbl(SqlConnection conn, studentjson StudentObj)
            {
                try
                {
                    string query = @"INSERT INTO [dbo].[student] ([student]) VALUES (@student)";
                    using (SqlCommand cmd = new SqlCommand(query, conn))
                    {
                        cmd.Parameters.Add(new SqlParameter("@student", StudentObj.student));
                        cmd.ExecuteNonQuery();
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

    Regards

    Monday, January 29, 2018 9:42 PM
  • User-1396990745 posted

    Hi, I am able to read json data contents here from the source.

    IList<SData> StudentList = studentjson.data;

    But, not being able to write its content to the table.

    Tuesday, January 30, 2018 5:50 AM
  • User283571144 posted

    Hi vscsl,

    vscsl

    Hi, I am able to read json data contents here from the source.

    IList<SData> StudentList = studentjson.data;

    But, not being able to write its content to the table.

    As far as I know, the web api could automatic deserialize the json to right format.

    As bruce codes shows, if you use the right class, you could directly get the list of the data as the codes shows.

    Besides, I suggest you could set a breakpoint in that codes to check which the list of the data you have get and check the student has the value.

    Best Regards,

    Brando

    Wednesday, January 31, 2018 8:11 AM