Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize using Newtonsoft in C#

Tags:

json

c#

json.net

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.

like image 289
Sri Hari Krishna Yalamanchili Avatar asked Sep 02 '25 15:09

Sri Hari Krishna Yalamanchili


1 Answers

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; }
}

Screenshot for the output

like image 93
Mohit S Avatar answered Sep 05 '25 06:09

Mohit S