I am relatively new to working with C# (v5.0) and Json data (Newtonsoft.Json v6.0) and am seeking assistance in resolving an error when attempting to populate a .Net 4.5 GridView control. My sample Json data as returned by a web service is:
{
PersonDetails: [
{
Book: "10 ",
FirstName: "Delbert",
LastName: "Hinson",
Remarks: null
},
{
Book: "5 ",
FirstName: "GUY",
LastName: "HINSON",
Remarks: null
},
{
Book: "13 ",
FirstName: "JAMES",
LastName: "HINSON",
Remarks: null
},
{
Book: "7 ",
FirstName: "JOHN, SR",
LastName: "HINSON",
Remarks: null
}
]
}
My class, as generated by Json2CSharp.com is:
namespace VAPerson
{
public class PersonDetail
{
public string Book { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public object Remarks { get; set; }
}
public class RootObject
{
public List<PersonDetail> PersonDetails { get; set; }
}
}
My deserialization code is:
protected void Page_Load(object sender, EventArgs e)
{
string lastName = "hinson";
var url = string.Format(baseUrl, lastName);
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);
var personDetail = JsonConvert.DeserializeObject<RootObject>(content);
GridView1.DataSource = personDetail;
GridView1.DataBind();
}
The deserialization works properly, returning 4 rows of data. When attempting to specify the GridView.DataSource I receive the error:
Data source is an invalid type. It must be either an IListSource, IEnumerable or IDataSource.
It appears that I need to convert the deserialized results to an acceptable format as indicated by the error message. In my research to date, I have been unable to accomplish this. Any help, sample code and suggestions is greatly appreciated.
Thank you - Duane.
You're binding the container object, not the list itself. Change it to:
GridView1.DataSource = personDetail.PersonDetails;
And it should work.