Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"System.ArgumentException: 'No mapping exists from object type Newtonsoft.Json.Linq.JValue to a known managed provider native type.'

I'm trying to insert data from a JSON Array response that I've gotten as a response. However, I keep getting a "System.ArgumentException: 'No mapping exists from object type Newtonsoft.Json.Linq.JValue to a known managed provider native type.'" error thrown at me. The code and JSON array that I have is as follows:

I've tried googling, asking my peers for the answers but to no avail. I was wondering, since being serialized, do JSON objects need to be changed before it can be saved to a database? At the same time, the most frequent answer that I have been given was to add in the extension of .Text as my responses come in a text field area.

JSON Array:

    "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()
}

As mentioned, the error gets thrown with the message "'No mapping exists from object type Newtonsoft.Json.Linq.JValue to a known managed provider native type."

like image 759
Dan Zainal Avatar asked Sep 06 '25 20:09

Dan Zainal


1 Answers

try like this , i.e. just add .ToString()` as given in below code as rror comes from sending an object as a parameter value. It needs to be a string, int, bool, etc.

 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
    }
like image 136
Pranay Rana Avatar answered Sep 08 '25 10:09

Pranay Rana