Sdílet prostřednictvím


Downloading JSON data

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Downloading and processing data from web sites is a common task, and here's how to do the equivalent of iOS's [NSData dataWithContentsOfURL] in Windows 8.1 and Windows Phone 8.1.

Reading data in JSON format from a web site is an easy way to get live data into your app. Windows 8.1 and Windows Phone 8.1 includes the HttpClient class which will quickly pull data down over a network connection. Here's a simple C# example that connects to a web site, and loads the first page:

 async private void ReadDataFromWeb()
        {
            var client = new HttpClient(); // Add: using System.Net.Http;
            var response = await client.GetAsync(new Uri("https://www.microsoft.com"));
            var result = await response.Content.ReadAsStringAsync();

            // Display data read from web site
            Debug.WriteLine(result);
        }

To process data loaded from a web server, use an object such as JsonList or JsonArray from Windows.Data.Json to break out the individual parts of the JSON string. Here's example code that takes data from a string:

            var jstring = "[\"Mercury\",0,\"Venus\",0,\"Earth\",1,\"Mars\",2]";

            JsonValue jsonList = JsonValue.Parse(jstring); // Add: using Windows.Data.Json;

            var planet = jsonList.GetArray().GetStringAt(6);
            var moons = jsonList.GetArray().GetNumberAt(7);

            Debug.WriteLine(planet + " has " + moons + " moons");

Topics for iOS devs

Resources for iOS devs

Windows 8 controls for iOS devs

Windows 8 cookbook for iOS devs

JSON topics

Quickstart: Connecting using HttpClient (Windows Store apps using C#/VB/C++ and XAML)

Using JavaScript Object Notation (JSON)