3

Form a third party system deserialize json data to the object/class format and write data into a SQL Server table from a asp.net web api. When I run the below code I run into the following error

cannot convert json collection to string

I am using System.Web.Extensions dll to deserialize json data.

JSON:

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

My 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; }
}

My 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;
    }
}
10
  • Your post method does not have json argument .. and i don't think you need to serialize json in webapi.. you neee ti ellaborate a bit Commented Jan 30, 2018 at 5:17
  • @CodingYoshi: I still get cannot explicitly convert to type error. Commented Jan 30, 2018 at 5:32
  • @Aamir: Could you please let me point me to some example of not having to deserialize json in webapi. Commented Jan 30, 2018 at 5:34
  • IList<SData> StudentList = studentjson.data; Why you wrote this if you are not using StudentList anywhere. I feel this will break as you studentjson.data is string. Commented Jan 30, 2018 at 6:00
  • The model binder will deserialise your data automatically if you have a matching C# class. Your model is confusing though - you have a "Student" object as the input, then you expect there to be a "data" property on it, but that's not defined in your Student C# class, so is unlikely to exist. But why have a list of Students inside a single student? Structure makes no sense. And your code above will also not compile for other reasons. Is this your real code? Commented Jan 30, 2018 at 6:01

1 Answer 1

3

your model classes should be like this.

public class Student
{
    public string Id { get; set; }
    public string Student { get; set; }
    public string Grade { get; set; }
}

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

you do not need an extra serializer on web api. asp.net web api supports json-xml media types by default.

    [HttpPost]
    public IHttpActionResult Post(RequestModel studentjson)
    {
        string SQLConnectionString = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(SQLConnectionString))
        {
            conn.Open();
            try
            {
                foreach (var student in studentjson.data)
                {
                    if (writetotbl(conn, student.Student))
                    {
                        Console.WriteLine(string.Format("Id:{0}, Student:{1}, Grade:{2}", student.Id, student.Student, student.Grade));
                    }
                    else
                    {
                        Console.WriteLine("Error : " + student.Student);
                    }
                }
                conn.Close();
            }
            catch (Exception ex)
            {
                // make sure the connection is closed
                if (conn.State != System.Data.ConnectionState.Closed)
                    conn.Close();
                throw;
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.