Cannot deserialize the current JSON array (e.g. [1,2,3])
I think the problem you're having is that your JSON is a list of objects when it comes in and it doesnt directly relate to your root class.
var content
would look something like this (i assume):
[
{
"id": 3636,
"is_default": true,
"name": "Unit",
"quantity": 1,
"stock": "100000.00",
"unit_cost": "0"
},
{
"id": 4592,
"is_default": false,
"name": "Bundle",
"quantity": 5,
"stock": "100000.00",
"unit_cost": "0"
}
]
Note: make use of http://jsonviewer.stack.hu/ to format your JSON.
So if you try the following it should work:
public static List<RootObject> GetItems(string user, string key, Int32 tid, Int32 pid)
{
// Customize URL according to geo location parameters
var url = string.Format(uniqueItemUrl, user, key, tid, pid);
// Syncronious Consumption
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);
return JsonConvert.DeserializeObject<List<RootObject>>(content);
}
You will need to then iterate if you don't wish to return a list of RootObject
.
I went ahead and tested this in a Console app, worked fine.
That's because the json you're getting is an array of your RootObject
class, rather than a single instance, change your DeserialiseObject<RootObject>
to be something like DeserialiseObject<RootObject[]>
(un-tested).
You'll then have to either change your method to return a collection of RootObject
or do some further processing on the deserialised object to return a single instance.
If you look at a formatted version of the response you provided:
[
{
"id":3636,
"is_default":true,
"name":"Unit",
"quantity":1,
"stock":"100000.00",
"unit_cost":"0"
},
{
"id":4592,
"is_default":false,
"name":"Bundle",
"quantity":5,
"stock":"100000.00",
"unit_cost":"0"
}
]
You can see two instances in there.
You can use this to solve your problem:
private async void btn_Go_Click(object sender, RoutedEventArgs e)
{
HttpClient webClient = new HttpClient();
Uri uri = new Uri("http://www.school-link.net/webservice/get_student/?id=" + txtVCode.Text);
HttpResponseMessage response = await webClient.GetAsync(uri);
var jsonString = await response.Content.ReadAsStringAsync();
var _Data = JsonConvert.DeserializeObject <List<Student>>(jsonString);
foreach (Student Student in _Data)
{
tb1.Text = Student.student_name;
}
}