Click here to Skip to main content
15,885,953 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. im trying to insert data from a JSON Array response that ive 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 that i have is as follows:

private void btnSave_Click(object sender, EventArgs e)
{


string connectionString;
connectionString = @"Data Source=LAPTOP-R0HOA2B6;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();





}
con.Close();

What I have tried:

Best ive done is that i have tried is googling. Im really really bad at coding. Any/all help is appreciated.
Posted
Updated 23-Jul-19 21:10pm

1 solution

You need to use a concrete type that maps the JSON into a class structure that your code can work with. Use something like this (I don't know the exact structure as you haven't specified it, but you get the idea).

C#
[DataContract]
public class Device
{
  [DataMember]
  public int Device {get; set;}

  [DataMember]
  public DateTime Time {get; set;}

  [DataMember]
  public string Data {get; set;}
}
Then in your code, deserialise your response into this instead.
C#
Device jsonObj = JsonConvert.DeserializeObject<Device>(txtResponse.Text);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900