我的json看起来像:
[
{
fid: "1",
forum_name: "Latest Product News",
imagepath: "http://sourcingmachine.co.uk/iphone_images/news_icons/product-news.png"
},
{
fid: "19",
forum_name: "Latest Supplier News",
imagepath: "http://sourcingmachine.co.uk/iphone_images/news_icons/supplier-news.png"
}
]
如何在列表框中获取此数据?
我现在已经这样做了:
public MainPage()
{
InitializeComponent();
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += webclient_DownloadStringCompleted;
webclient.DownloadStringAsync(new Uri("MyURI"));
}
private void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Result))
{
var rootObject = JsonConvert.DeserializeObject<RootObject>(data);
this.DataContext = rootObject;
}
}
这是我的RootObject类
public class RootObject
{
[JsonProperty(PropertyName = "fid")]
public string fid { get; set; }
[JsonProperty(PropertyName = "forum_name")]
public string forum_name { get; set; }
[JsonProperty(PropertyName = "imagepath")]
public string imagepath { get; set; }
}
如何将结果分配给我的ListBox.ItemSource
?
答案 0 :(得分:2)
public class YourModelObject
{
public int fid { get;set; }
public string forum_name { get;set; }
public string imagepath { get;set; }
}
从JSON字符串调用转换时
string yourJSON = "what you posted above";
var values = JsonConvert.DeserializeObject<List<RootObject>>(yourJSON);
//values is a List<RootObject> if it succeds
答案 1 :(得分:-2)
InitializeComponent();
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += webclient_DownloadStringCompleted;
webclient.DownloadStringAsync(new Uri("Your URI"));
private void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
string data = e.Result;
if (!string.IsNullOrEmpty(data))
{
var rootObject = JsonConvert.DeserializeObject<List<GetNews>>(data);
lstNews.ItemsSource = rootObject;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
GetNews
class GetNews
{
public string fid { get; set; }
public string forum_name { get; set; }
public string imagepath { get; set; }
}