Start learning free

LESSON 3 OF 173 · BACKEND: HOW THE WEB WORKS

Read a JSON Answer in C#

Practice

Most APIs don't answer with sentences but with JSON, the text format they use to send data. It describes arrays and objects, but it arrives as text: ReadAsStringAsync() would give you only a string.

await response.Content.ReadFromJsonAsync<JsonElement>() reads that text and gives you a JsonElement, C#'s view of the JSON. A JSON […] is an array: GetArrayLength() counts it, [0] reads its first item and EnumerateArray() loops over it. A JSON {…} is an object: GetProperty("key") reads one value. For a weather API whose body is {"city": "Paris", "temp": 18}:

var weather = await response.Content.ReadFromJsonAsync<JsonElement>();
Console.WriteLine(weather.GetProperty("city") + " " + weather.GetProperty("temp"));   // Paris 18

The supplier's price list is at the path /prices. Its body is an array of products, and each product is an object with an "id", a "name" and a "price". Your program must print:

5 products
{"id":1,"name":"Mug","price":5}
Mug costs 5
Notebook costs 3
Lamp costs 14
Pen costs 1
Plant costs 6

Your task: request /prices, read the body with ReadFromJsonAsync<JsonElement>() and keep it in products, print how many products there are and the first one, then loop over the array and print each product's name and price.


Assignment
Follow the Coding Tutorial to read the supplier's price list as JSON and print every product's name and price.


Hint
products is a JSON array of objects: GetArrayLength() counts its items, products[0] is the first object, and inside the loop each product is read with GetProperty, with the key's name in quotes.


STEP 1 OF 6
    Ctrl + Enter to check

    Web Json Answer in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free