使用C#导入JSON数据

3

从第三方系统反序列化JSON数据为对象/类格式,并从asp.net web api将数据写入SQL Server表。 当我运行以下代码时,遇到以下错误

无法将JSON集合转换为字符串

我使用System.Web.Extensions dll来反序列化JSON数据。

JSON:

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

我的模型:

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

我的控制器:

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

@CodingYoshi:我仍然得到了“无法显式转换为类型”的错误。 - pbj
如果您有一个匹配的C#类,模型绑定器将自动反序列化您的数据。但是您的模型很混乱 - 您将“Student”对象作为输入,然后期望在其上有一个“data”属性,但是在您的Student C#类中未定义该属性,因此不太可能存在。但是为什么要在单个学生内部拥有学生列表?结构毫无意义。而且您上面的代码也无法编译,原因还有其他。这是您真正的代码吗? - ADyson
@Aamir:我已经在原始帖子中添加了JSON,并尝试将这些数据写入表格。 - pbj
你可以使用Newtonsoft,将参数类型更改为JObject,然后将其反序列化为IList<Student>或尝试反序列化为AllStudents。 - Aamir Masood
什么是 SData - Lasse V. Karlsen
显示剩余5条评论
1个回答

3
您的模型类应该像这样。
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; }
}

在Web API上您不需要额外的序列化程序,因为ASP.NET Web API默认支持JSON-XML媒体类型。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接