2

I am using the Flurl library to call a webservice, which returns a JSON

{"data":{"charges":[{"code":30200757,"reference":"","dueDate":"18/12/2018","checkoutUrl":"https://sandbox.boletobancario.com/boletofacil/checkout/C238E9C42A372D25FDE214AE3CF4CB80FD37E71040CBCF50","link":"https://sandbox.boletobancario.com/boletofacil/charge/boleto.pdf?token=366800:m:3ea89b5c6579ec18fcd8ad37f07d178f66d0b0eb45d5e67b884894a8422f23c2","installmentLink":"https://sandbox.boletobancario.com/boletofacil/charge/boleto.pdf?token=30200757:10829e9ba07ea6262c2a2824b36c62e7c5782a43c855a1004071d653dee39af0","payNumber":"BOLETO TESTE - Não é válido para pagamento","billetDetails":{"bankAccount":"0655/46480-8","ourNumber":"176/30200757-1","barcodeNumber":"34192774200000123001763020075710655464808000","portfolio":"176"}}]},"success":true}

This is my F# code:

let c = "https://sandbox.boletobancario.com/boletofacil/integration/api/v1/"
        .AppendPathSegment("issue-charge")
        .SetQueryParams(map)
        .GetJsonAsync()

c.Wait()
let j = c.Result
let success = j?success

I checked and the variable j contains an obj ("System.Dynamic.ExpandoObject")

How can I access, for example, the success value of this obj in variable j? And how to access the data ?

Visual Studio 2019 Screenshot

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Tony
  • 16,527
  • 15
  • 80
  • 134

2 Answers2

4

I don't have experience with that particular library, but if the result is just a normal ExpandoObject, then the following should do the trick.

First of all, ExpandoObject implements the IDictionary<string, obj>, so you can cast the value to IDictionary and then add or get members as you wish:

open System.Dynamic
open System.Collections.Generic

let exp = ExpandoObject() 

// Adding and getting properties using a dictionary    
let d = exp :> IDictionary<string, obj>
d.Add("hi", 123)
d.["hi"]

If you want to use the ? syntax, you can define the ? operator yourself, doing exactly the same as above:

let (?) (exp:ExpandoObject) s = 
  let d = exp :> IDictionary<string, obj>
  d.[s]

exp?hi

That said, if you can use type providers, it'd be a lot easier to do this with F# Data for the JSON parsing, because then you could just replace all the dynamic unsafe ? accesses with type-checked ones!

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
1

You can use a predefined ? operator for all your DynamicObject interop needs with fsprojects/FSharp.Interop.Dynamic

open FSharp.Interop.Dynamic
let ex1 = ExpandoObject()
ex1?Test<-"Hi"//Set Dynamic Property
ex1?Test //Get Dynamic
jbtule
  • 31,383
  • 12
  • 95
  • 128