我正在尝试从作为响应获得的 JSON 数组响应中插入数据。但是,我不断收到“System.ArgumentException:‘不存在从对象类型 Newtonsoft.Json.Linq.JValue 到已知托管提供程序 native 类型的映射。’”向我抛出的错误。我拥有的代码和 JSON 数组如下:
我试过谷歌搜索,向我的同行询问答案但无济于事。我想知道,自从被序列化后,JSON 对象是否需要更改才能保存到数据库?同时,我收到的最常见答案是添加 .Text 的扩展名,因为我的回复来自文本字段区域。
JSON 数组:
"data": [
{
"device": "deviceone",
"time": 2359,
"data": "0000th34"
}]
private void btnSave_Click(object sender, EventArgs e)
{
string connectionString;
connectionString = @"Data Source=LAPTOP-JOHN;Initial Catalog=DemoDb; User ID=John;Password=1234";
SqlConnection con = new SqlConnection(connectionString);
//Opens the connection to the database
con.Open();
dynamic jsonObj = JsonConvert.DeserializeObject(txtResponse.Text);
using (SqlCommand cmd = new SqlCommand("Insert into devicedata(device,time,data) VALUES (@device,@time,@data)", con))
{
cmd.Parameters.AddWithValue("@device", jsonObj.data[0].device);
cmd.Parameters.AddWithValue("@time", jsonObj.data[0].time);
cmd.Parameters.AddWithValue("@data", jsonObj.data[0].data);
cmd.ExecuteNonQuery(); // Running the code will result in the error being thrown
}
con.Close()
}
如前所述,将抛出错误并显示消息“'不存在从对象类型 Newtonsoft.Json.Linq.JValue 到已知托管提供程序 native 类型的映射。”
最佳答案
像这样尝试,即只需按照下面的代码添加 .ToString()`,因为错误来自于将对象作为参数值发送。它需要是字符串、int、bool 等。
using (SqlCommand cmd = new SqlCommand("Insert into devicedata(device,time,data) VALUES (@device,@time,@data)", con))
{
cmd.Parameters.AddWithValue("@device", jsonObj.data[0].device.ToString());
cmd.Parameters.AddWithValue("@time", jsonObj.data[0].time.ToString());
cmd.Parameters.AddWithValue("@data", jsonObj.data[0].data.ToString());
cmd.ExecuteNonQuery(); // Running the code will result in the error being thrown
}
关于c# - "System.ArgumentException: ' 不存在从对象类型 Newtonsoft.Json.Linq.JValue 到已知托管提供程序 native 类型的映射。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57176239/