Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 10 Remote Data

Webservices

Webservices act as a mechanism to query or obtain data from a remote server. They typically offer many advantages to developers building them because they provide the ability to charge based on usage, protect the developer’s intellectual property, and other reasons.

The Open Weather API

You will be calling the Open Weather API and specifically version 2.5 of the OneCall API. The API is free to use with some usage limits. You can call it up to 60 times per minute and 1,000,000 calls per month, which will certainly be fine for this scenario.

For the initial work, you will be using a fixed latitude and longitude of 20.7984 and -156.3319, respectively, which if you look it up represents Maui, Hawaii. You will enabling the application to use the device’s current location information in the next chapter.

Creating an Open Weather Account

You will be required to create an account. To do so, navigate to the website at https://home.openweathermap.org/users/sign_up and create the account. Note that you do not need to enter any billing details. You can use it entirely for free. If you breach the call limits, the API will simply fail instead of running into accidental charges.

Creating an Open Weather API key

Next, you need to create an API key, which can be done on the following page at https://home.openweathermap.org/api_keys. Keep a copy of this API key ready for when you eventually use it later in this chapter. Don’t worry too much for now as you can return to the above web page and access the key.

302

Chapter 10 Remote Data

Examining theData

Before you dive into writing some code, you should take a look at the API and the data that it returns. In fact, the API offers a lot more detail than you really need. You can consume the details in case you want to use them in the future; however, this does bring in some possible drawbacks. It increases the complexity of reading through the data if you need to debug things, and it also increases the amount of data that needs to be retrieved by your application. In the mobile world, this can be expensive!

Given the above, you can make the following web service call which includes following details:

•\

Calls version 2.5 of the OneCall API

•\

Supplies latitude of 20.7984

•\

Supplies longitude of -156.3319

•\

Supplies units of metric, meaning you will receive

 

degrees Celsius

•\

Supplies exclude of minutely, hourly, daily, alerts,

 

meaning you will only receive the current weather data

•\

Supplies the api key you created in the previous section

The full URL that you need to call looks as follows:

https://api.openweathermap.org/data/2.5/onecall?lat=20.7984& lon=-156.3319&units=metric&exclude=minutely,hourly,daily,alerts &appid=APIKEY

You can open this in any web browser to view the following response back. You can see the key details that you will need for your application highlighted in bold.

{

"lat": 20.7984, "lon": -156.3319,

303

Chapter 10 Remote Data

"timezone": "Pacific/Honolulu", "timezone_offset": -36000,

"current": {

"dt": 1663101650, "sunrise": 1663085531, "sunset": 1663129825,

"temp": 20.77, "feels_like": 21.15, "pressure": 1017, "humidity": 86, "dew_point": 18.34, "uvi": 7.89, "clouds": 75, "visibility": 10000, "wind_speed": 5.66, "wind_deg": 70,

"weather": [

{

"id": 501,

"main": "Rain",

"description": "moderate rain",

"icon": "10d"

}

], "rain": {

"1h": 1.78

}

}

}

304

Chapter 10 Remote Data

Using System.Text.Json

In order to consume and deserialize the contents of the JSON returned to you, you need to use one of the following two options:

•\ Newtonsoft.Json (requires a NuGet package)

•\ System.Text.Json

Newtonsoft has been around for many years and is a go-to option for many developers. System.Text.Json has become its successor and is my recommendation for this scenario, especially as it is backed by Microsoft and James Newton-King, the author of Newtonsoft, works for Microsoft.

Let’s go ahead and use System.Text.Json as it is the recommended way to proceed and ships with .NET MAUI out of the box.

Now that you have seen what the data looks like, you can start to build the model classes that will allow you to deserialize the response coming back from the API.

Creating Your Models

I highlighted that you really don’t need all of the information that is returned from the API. Thankfully you only need to build your model to cover the detail that you require and allow the rest to be ignored during the deserialization process.

Let’s create the model classes you require. You do this in the reverse order that they appear in the JSON due to the fact that the outer elements need to refer to the inner elements.

First, add a new folder to keep everything organized and call it

Communications.

Now, add a new class file and call it Weather.cs.

namespace WidgetBoard.Communications;

public class Weather

305

Chapter 10 Remote Data

{

public string Main { get; set; }

public string Icon { get; set; }

public string IconUrl => $"https://openweathermap.org/img/ wn/{Icon}@2x.png";

}

Your Weather class maps to the weather element in the JSON returned from the API. You can see that you are mapping to the main and icon elements and you have added a calculated property that returns a URL pointing to the icon provided by the Open Weather API. The last property you are mapping, IconUrl, is yet another great example of remote data. The API provides you with an icon that can be rendered inside your application representing the current weather of the location. Based on the example in your original JSON, you see the icon value of 10d. This represents rain.

You will notice that the casing of your property names does not match the element names in the JSON. This will actually result in the deserialization process to mapping as you require. When you get to the deserialization part, you will see how to handle this scenario.

Your next model class to add should be called Current and, similarly to the Weather class, it will map to the element that matches its name: current. Your Current class file should have the following contents:

using System.Text.Json.Serialization;

namespace WidgetBoard.Communications;

public class Current

306

Chapter 10 Remote Data

{

[JsonPropertyName("temp")]

public double Temperature { get; set; }

public int Sunrise { get; set; }

public int Sunset { get; set; }

public Weather[] Weather { get; set; }

}

This class will contain an array of Weather, the Sunset and Sunrise times, and the current Temperature. With the Temperature property mapping, you can see how it is possible to map from a property in your model to an element in JSON that has a different name. This functionality is extremely valuable when building your own models because it allows you to name the properties to provide better context. I personally prefer to avoid abbreviations and stick with explicit names to make the intentions of the code clear.

Your final model class to add should be called Forecast.cs and will have the following contents:

namespace WidgetBoard.Communications;

public class Forecast

{

public string Timezone { get; set; }

public Current Current { get; set; }

}

This class maps to the top-level element in the returned JSON. You are mapping to the Timezone element and also the Current, which will contain your previously mapped values.

307