如何在不断变化的 Rest/JSON 端点上使用 F# 类型提供程序?

How are F# Type Providers used on a changing Rest/JSON Endpoint?

我正在尝试使用 F# 类型的提供程序在我的应用程序中包含天气数据。我正在使用 OpenWeatherMap.org 来获取当前的天气数据。 https://openweathermap.org/current

有时 OpenWeatherMap 响应不显示任何 JSON 下雨(例如,有 1 小时 window 没有下雨)。

所以如果我这样做:

type WeatherForecast= JsonProvider<"http://api.openweathermap.org/data/2.5/weather?lat=39.64&lon=-74.28&appid=MyKeyICantSharePublicly">
...
let mydata = WeatherForecast.Load("http://api.openweathermap.org/data/2.5/weather/?lat=12&lon=12&appid=MyKeyICantSharePublicly)

printf "%s" (string mydata.Rain.``1h``)

printf 语句将失败,因为它并不总是知道 mydata.Rain 是什么,因为类型提供程序不再提供 Rain 信息。

根据我尝试编译我的应用程序的时间,构建将因类型提供程序而失败。

如何将类型提供程序与这样一个不断变化的 Rest/Json 端点一起使用?

示例数据。

{
  "coord": {
    "lon": -74.28,
    "lat": 39.64
  },
  "weather": [
    {
      "id": 701,
      "main": "Mist",
      "description": "mist",
      "icon": "50d"
    },
    {
      "id": 721,
      "main": "Haze",
      "description": "haze",
      "icon": "50d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 7.71,
    "pressure": 1012,
    "humidity": 93,
    "temp_min": 7,
    "temp_max": 9.4
  },
  "visibility": 4023,
  "wind": {
    "speed": 5.7,
    "deg": 2...

而不是 url,您应该提供一些有雨和无雨的样本:

type People = JsonProvider<""" 
  [ { "name":"John", "age":94 }, 
    { "name":"Tomas" } ] """, SampleIsList=true>

for item in People.GetSamples() do 
  printf "%s " item.Name 
  item.Age |> Option.iter (printf "(%d)")
  printfn ""

上面的示例有两条记录,一条包含 age,另一条不包含。这使得 age 字段成为 int option

来自文档:http://fsharp.github.io/FSharp.Data/library/JsonProvider.html