“ System.ArgumentException:'不存在从对象类型Newtonsoft.Json.Linq.JValue到已知托管提供程序本机类型的映射。

还有Zainal

我正在尝试从响应中获取的JSON数组响应中插入数据。但是,我不断收到“ System.ArgumentException:'从对象类型Newtonsoft.Json.Linq.JValue对象类型到已知的托管提供程序本机类型不存在映射。'”错误向我抛出。我拥有的代码和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到已知托管提供程序本机类型的映射存在”引发错误。

普兰尼·拉娜(Pranay Rana)

尝试这样,即按照下面的代码添加.ToString()`,因为rror来自发送对象作为参数值。它必须是字符串,整数,布尔值等。

 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
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章