我正在尝试将 WebApi 应用程序与 Windows RT 应用程序连接起来。我从页面正确接收 Json。我从 JSON 数组异步获取所有元素唯一的问题是嵌套数组返回 null 但是当我调试 json 字符串内部有元素
这里是 MVC 4 和 WinRT 的图像和代码
StudentCollection.cs
private async void GetStudents() {
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(new Uri("http://localhost:17775/api/Students"));
var json = await response.Content.ReadAsStringAsync();
var jsarray = JsonArray.Parse(json);
GetStudentsbyJson(jsarray);
}
private void GetStudentsbyJson(JsonArray result)
{
foreach( var item in result)
{
Student student = new Student();
Course course ;
var obj = item.GetObject();
foreach (var key in obj.Keys)
{
IJsonValue value;
if(!obj.TryGetValue(key,out value))
continue;
switch (key)
{
case "ID":
student.ID = Int32.Parse(value.GetNumber().ToString());
break;
case "Name":
student.Name = value.GetString();
break;
case "Age":
student.Age = Int32.Parse(value.GetNumber().ToString());
break;
case "HasScholarship":
student.HasScholarship = value.GetBoolean();
break;
case "Course":
course= GetCourseJson( value.GetObject());
break;
case "Sex":
student.Sex = value.GetString();
break;
}
}
if (student != null)
_students.Add(student);
}
}
private Course GetCourseJson(JsonObject jsonObject)
{
var course = new Course();
foreach (var key in jsonObject.Keys)
{
IJsonValue value;
if (!jsonObject.TryGetValue("keys", out value))
continue;
switch (key) {
case "CourseId":
course.CourseId = Int32.Parse(value.ToString());
break;
case "Name":
course.Name = value.GetString();
if (course.Name == null)
throw new NullReferenceException("No Name added");
break;
}
}
return course != null ? course : new Course() {Name="Contabilidade" };
}
主页.xaml
<GridView ItemsSource="{Binding Students}" SelectedIndex="{Binding SelectedStudent, Mode=TwoWay}" Padding="24">
<GridView.Background>
<ImageBrush/>
</GridView.Background>
<GridView.ItemTemplate>
<DataTemplate >
<Grid Width="200" Height="150">
<Grid.Background>
<SolidColorBrush Color="Gold"/>
</Grid.Background>
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom">
<StackPanel.Background>
<SolidColorBrush Color="Red" Opacity=".3" />
</StackPanel.Background>
<TextBlock Text="{Binding Name}" Padding="12,0,12,0"/>
<TextBlock Text="{Binding Course.Name}" />
<TextBlock Text="{Binding Age}"/>
</StackPanel>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
[{"Course":{"CourseId":1,"Name":"Engenharia Informatica"},"ID":1,"Name":"Oldemiro","Age":20,"Sex":"male","HasScholarship":true},{"Course":{"CourseId":1,"Name":"Engenharia Informatica"},"ID":2,"Name":"Teotonio","Age":20,"Sex":"male","HasScholarship":false},{"Course":{"CourseId":1,"Name":"Engenharia Informatica"},"ID":3,"Name":"Ivan Ernesto","Age":21,"Sex":"male","HasScholarship":true},{"Course":{"CourseId":1,"Name":"Engenharia Informatica"},"ID":4,"Name":"Severino Mateus","Age":20,"Sex":"male","HasScholarship":true}]