gpt4 book ai didi

c# - 使用c#导入json数据

转载 作者:行者123 更新时间:2023-11-30 15:55:31 27 4
gpt4 key购买 nike

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

cannot convert json collection to string

我正在使用 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; }
}

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

最佳答案

你的模型类应该是这样的。

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

关于c# - 使用c#导入json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48514279/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com