Reputation: 33
I'm able to download and deserialize a JSON string (below) from an external database, but for the life of me, cannot figure out the specific steps to convert it into individual entries in a listbox.
Looking through responses from others re: similar requests, I can't seem to make it work - for a number of reasons (e.g. outdated (WP7), lack of 'Using' directives, non-Windows-Phone, etc.).
Can someone please assist to provide the code I should use to take the above json string, and turn it into a usable dataset to populate entries in a ListBox?
(yes, I'm a C# novice, but should be able to take your simple advice and run with it).
Thanks in advance!
Upvotes: 1
Views: 127
Reputation: 2105
I'm pretty sure that the json you are getting is more like this(your list probably has some name):
{"records" :[{"Source_ID":"1","Source_Code":"AL-MONTG-M","Source_Name":"Montgomery Adviser","Source_Desc":"Montgomery
Adviser","Source_Auth":"YES","Source_Image":null,"Source_URL":"http://www.montgomeryadvertiser.com/","Source_Region":"Alabama","Source_City":"Montgomery","Source_Country":"USA"},{"Source_ID":"2","Source_Code":"WA-SEATTL-","Source_Name":"Seattle Post-Intelligencer","Source_Desc":"Seattle
Post-Intelligencer","Source_Auth":"YES","Source_Image":null,"Source_URL":"http://www.seattlepi.com/","Source_Region":"Washington","Source_City":"Seattle","Source_Country":"USA"},{"Source_ID":"3","Source_Code":"AUSL-PERTH","Source_Name":"The West
Australian","Source_Desc":"https://au.news.yahoo.com/thewest/","Source_Auth":"YES","Source_Image":null,"Source_URL":"https://au.news.yahoo.com/thewest/","Source_Region":"Western-Australia","Source_City":"Perth","Source_Country":"Australia"}]}
The first thing you should do is extracting classes from it, http://json2csharp.com/ is going to help you with this. Just paste your json on this website and you are going to get 2 classes:
public class Record
{
public string Source_ID { get; set; }
public string Source_Code { get; set; }
public string Source_Name { get; set; }
public string Source_Desc { get; set; }
public string Source_Auth { get; set; }
public object Source_Image { get; set; }
public string Source_URL { get; set; }
public string Source_Region { get; set; }
public string Source_City { get; set; }
public string Source_Country { get; set; }
}
public class RootObject
{
public List<Record> records { get; set; }
}
To deserialize I recommend you to use Json.NET framework, it makes it easy:
RootObject r = JsonConvert.DeserializeObject<RootObject>(*json*);
Now, when you have your list, you can attach it to your listbox like this:
listbox.DataSource = r.records;
It should work just fine. To change the way it shows your data, you should either override ToString method of Record class or modify your list's ItemTemplate. Read about ObservableCollection<>(or implementing INotifyPropertyChanged), if you want your listbox to update after changing your List<>.
Upvotes: 1