MurdurFloor MurdurFloor - 8 months ago 91
reST (reStructuredText) Question

Converting JSON response string to a UWP gridview datasource

I have the following code that successfully retrieves a JSON string from a database. I now want to display this information in a gridview on the client side though im not sure how to do this.

if (response.IsSuccessStatusCode)
{
string strJson = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(strJson);
//apply to my grid view
}


Any help is appreciated

Answer Source

You have to deserialize object eg. with newtonsoft library. To do that use attributes or create deserializer manually, but you have to create a class or structure which represents database data.

If eg. your json looks like this :

{
  "Name":"Aleks",
  "City": "N.Y."
}

Try to create class:

public class Person{
  public string Name {get;set;}
  public string City {get;set;}  
}

And in your condition

if (response.IsSuccessStatusCode){
string strJson = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(strJson);
Person person = JsonConvert.DeserializeObject<Person>(strJson);    
}

To show it at GridView you have to declare GridView in xaml:

<GridView x:Name="test" DataTemplate="{StaticResource YourTemplate}"/>

And in codebehind

 test.ItemSource = new List<Preson>(){person};

DataTemplate is also needed.

<GridView x:Name="test">
<GridView.ItemTemplate>
 <DataTemplate>
  <StackPanel>
   <TextBlock Text{Binding Name}/>
   <TextBlock Text{Binding City}/>
  </StackPanel>
 </DataTemplate>
</GridView.ItemTemplate>
</GridView>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download