4

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.

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

That's what I just started typing, but you were faster :)
@YalamanchiliHari, instead of copy pasting, try to understand the code and then use it. Also, read and comprehend the error message first. Its a matter of capitalization in the name.
Thanks for the help again :)
@YalamanchiliHari Another way of saying thanks on SO would be upvoting. Well you are welcome. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.