假设这是我通过API收到的JSON数据......
var client = new HttpClient();
var uri = new Uri("blabla.com");
var response = await client.GetAsync(uri);
string result = await response.Content.ReadAsStringAsync();
[
{
" id":" 1",
"title": "Test_rom",
"subtitle": "",
"icon": "http://lpl.info/Admin/upload/cat.1.png"
},
{
"id": "2",
"title": "Jewelry",
"subtitle": "",
"icon": "http://lpl.info/Admin/upload/cat.2.png"
},
{
"id": "3",
"title": "Jackets",
"subtitle": "All sizes available",
"icon": "http://lpl.info/Admin/upload/cat.3.png"
}
] 在此之后我创建了一个类RootObject ... 公共类RootObject {
public string id {get;组; }
public string title { get; set; }
public string subtitle { get; set; }
public string icon { get; set; }
}
NoW我只想显示" title"的值。键...(使用C#)
RootObject TotalList = new RootObject();
string hub =" &#34 ;;
foreach(TotalList.title中的var d)
{hub = hub +" " + d.ToString(); }
ResultsText.Text =毂;
但这是错误的..plz帮助
答案 0 :(得分:0)
也许不是等待你应该使用。 Await将继续处理而不等待响应,因此您将看到null。
var response = client.GetAsync(uri).Result;
您不应该遍历您的类对象字段。这是错误的
foreach (var d in TotalList.title)
{hub = hub + " " + d.ToString(); }
如果填充了TotalList(您应该能够在调试器中看到它),则可以使用
访问title的值TotalList.title
我希望这对你有所帮助,不要放弃。
答案 1 :(得分:0)
我使用这种格式解决了这个问题......
private async void button_Click(object sender,RoutedEventArgs e)
{
var client = new HttpClient();
var uri = new Uri("http://blabla.com");
var response = await client.GetAsync(uri);
var result = await response.Content.ReadAsStringAsync();
RootObject TotalList = new RootObject();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<RootObject>));
List <RootObject> resu =(List<RootObject>)ser.ReadObject(ms);
string hub =&#34; &#34 ;;
foreach(Resu中的RootObject d)
{hub = hub +&#34; &#34; + d.title.ToString(); }
ResultsText.Text = hub;