I started building a Windows Phone app recently with the intent of pulling some JSON data from some random URI and I was pleasantly surprised to see the boiler plate template storing and retrieving JSON data  asynchronously from a local sample file as follows:

foreach (JsonValue groupValue in jsonArray)
{
    JsonObject groupObject = groupValue.GetObject();
    SampleDataGroup group = new SampleDataGroup(groupObject["UniqueId"].GetString(),
						groupObject["Title"].GetString(),
						groupObject["Subtitle"].GetString(),
						groupObject["ImagePath"].GetString(),
						groupObject["Description"].GetString());

    foreach (JsonValue itemValue in groupObject["Items"].GetArray())
    {
	JsonObject itemObject = itemValue.GetObject();
	group.Items.Add(new SampleDataItem(itemObject["UniqueId"].GetString(),
		itemObject["Title"].GetString(),
		itemObject["Subtitle"].GetString(),
		itemObject["ImagePath"].GetString(),
		itemObject["Description"].GetString(),
		itemObject["Content"].GetString()));
    }
    this.Groups.Add(group);	
}

Microsoft programmers have, for years, been shoe horned into all things XML (especially in non web scenarios) and this small, symbolic gesture was a nice surprise. Any way, this is how I ended up retrieving the JSON payload from the URI in question:

public sealed partial class MainPage : Page
{
	private HttpClient httpClient;
	private CancellationTokenSource cts;

	public MainPage()
	{
		this.InitializeComponent();
		this.NavigationCacheMode = NavigationCacheMode.Required;
	}
	
	protected override void OnNavigatedTo(NavigationEventArgs e)
	{
		if (httpClient != null)
		{
			httpClient.Dispose();
		}

		IHttpFilter filter = new HttpBaseProtocolFilter();
		httpClient = new HttpClient(filter);
		cts = new CancellationTokenSource();
	}
	
	private async void SendRequest()
	{
		try
		{
			var response = await httpClient.GetAsync(new Uri("http://www.ps.com/json/")).AsTask(cts.Token);
			var jsonSerializer = new DataContractJsonSerializer(typeof(MyCars));
			
			object objResponse = jsonSerializer.ReadObject((await response.Content.ReadAsInputStreamAsync()).AsStreamForRead());
			MyCars jsonResponse = objResponse as MyCars;
		}
        catch (Exception ex)
        {
			throw;
		}
	}
	
	private void Cancel_Click(object sender, RoutedEventArgs e)
    {
		cts.Cancel();
		cts.Dispose();

		// Re-create the CancellationTokenSource.
		cts = new CancellationTokenSource();
	}
		
	private void Button_Click(object sender, RoutedEventArgs e)
	{
		SendRequest();
	}		
}
		

[DataContract]
public class MyCars
{
	[DataMember]
	public string executionDateTime;

	[DataMember]
	public List salesList;
}

public class Sales
{
    [DataMember]
	public string id;
	
	[DataMember]
	public string stationName;
}

Is there a better way? Comments?

Related Posts:


Share on Twitter Facebook

Comment Section

Comments are closed.