I am trying to deserialize my JSON file in C# and getting error below: "An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code"
My JSON is:
[{"Yes":"52","No":"41"}]
My c# code is
public class survey
{
public string Yes { get; set; }
public string No { get; set; }
}
protected void Button1_Click(object sender, EventArgs e)
{
using (StreamReader r = new StreamReader("sample.json"))
{
string json = r.ReadToEnd();
var items = JsonConvert.DeserializeObject<survey>(json);
var a = items.Yes;
TextBox1.Text = a;
}
}
Can any one please help me.
It should be
JsonConvert.DeserializeObject<List<Survey>>(jsonstr);
Instead of
JsonConvert.DeserializeObject<survey>(json);
Because you are getting your JSON as an array of [Yes,No]
and then you will get the data like
var a = items[0].Yes;
Edit
The complete code might look like this
string jsonstr = File.ReadAllText("some.txt");
var items = JsonConvert.DeserializeObject<List<Survey>>(jsonstr);
var a = items[0].Yes;
The class looks like this
public class Survey
{
[JsonProperty("Yes")]
public string Yes { get; set; }
[JsonProperty("No")]
public string No { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With