Tom Rider
Tom Rider

Reputation: 2815

How to deserialize json object in C#

I am trying to deserialize the json string to a c# object.

string str ="[{ \"foo\" : \"A\" , \"bar\" : \"B\"}, { \"foo\" : \"C\" , \"bar\" : \"D\"}]";

public Class Example
{
  public string foo { get; set; }
  public string bar { get; set; }
}

JavaScriptSerializer Js = new JavaScriptSerializer();
Example[] ex = (Example[]) Js.DeserializeObject(str);

But I am getting an InvalidCast Exception. What am I doing wrong?

Upvotes: 0

Views: 2533

Answers (1)

L.B
L.B

Reputation: 116188

var list = new JavaScriptSerializer().Deserialize<List<FooBar>>(str);

public class FooBar
{
    public string foo;
    public string bar;
}

Upvotes: 7

Related Questions