xyncro / chiron

JSON for F#
https://xyncro.tech/chiron
MIT License
175 stars 41 forks source link

API Usage Question: Can I write this nicer? #8

Closed haf closed 9 years ago

haf commented 9 years ago

  type Account =
    { _url : Uri
      active : bool
      description : string
      number : uint16
      sru : uint16
      year : uint16 }
    static member FromJson (_ : Account) =
      (fun u a d n s y ->
        { _url        = Uri(u)
          active      = a
          description = d
          number      = n
          sru         = s
          year        = y })
      <!> Json.read "@url"
      <*> Json.read "Active"
      <*> Json.read "Description"
      <*> Json.read "Number"
      <*> Json.read "SRU"
      <*> Json.read "Year"
    static member ToJson (a : Account) =
      Json.write "@url" (a._url.ToString())
      *> Json.write "Active" a.active
      *> Json.write "Description" a.description
      *> Json.write "Number" a.number
      *> Json.write "SRU" a.sru
      *> Json.write "Year" a.year

  let getAccounts (context : ConfiguredApi) : Async<_> = async {
    let! resp = stdReq context Get "/accounts" |> getResponseAsync
    let json = resp.EntityBody |> Option.map Json.parse |> Option.get
    let (page : Page), (accounts : _ list) =
      match json with
      | Object values ->
        match values |> Map.find "Accounts" with
        | Array accounts ->
          values |> Map.find "MetaInformation" |> (Json.deserialize : _ -> Page),
          accounts |> List.map (Json.deserialize : _ -> Account)
        | x -> failwithf "unexpected %A" x
      | x -> failwithf "unexpected %A" x
    return PaginatedResult (accounts, resp, page)
  }

In particular where I want to zoom in on the object and pick out pieces of it.

haf commented 9 years ago

It would be great to see an example of deserialising a really complex nested object.

haf commented 9 years ago

Would this be useful:

  let inline maybeWrite key value =
    match value with
    | None ->
      fun json ->
        Value (), json
    | _ ->
       Json.write key value

When you don't want "null" tokens being written?

haf commented 9 years ago

maybeWrite would be great, now that I'm mapping this API where none of the keys are required to send, but I can't send nulls

haf commented 9 years ago

Closing due to lack of interest.