如何使用F#访问ExpandoObject属性?

时间:2018-12-08 22:17:37

标签: f# flurl

我正在使用Flurl库调用Web服务,但返回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}

这是我的F#代码:

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

我检查了一下,变量 j 包含一个obj(“ System.Dynamic.ExpandoObject”)

例如,如何在变量j中访问此obj的成功值? 以及如何访问数据

Visual Studio 2019 Screenshot

2 个答案:

答案 0 :(得分:4)

我没有使用该特定库的经验,但是如果结果只是正常的ExpandoObject,那么以下方法就可以解决问题。

首先,ExpandoObject实现了IDictionary<string, obj>,因此您可以将值强制转换为IDictionary,然后根据需要添加或获取成员:

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"]

如果要使用?语法,则可以自己定义?运算符,其操作与上述操作完全相同:

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

exp?hi

也就是说,如果您可以使用类型提供程序,那么使用F# Data进行JSON解析会容易得多,因为这样您就可以替换所有动态不安全的?访问与类型检查的!!

答案 1 :(得分:1)

您可以对https://github.com/jeffbrown/mcroteaucontrollertest使用预定义的?运算符来满足所有DynamicObject互操作需求

open FSharp.Interop.Dynamic
let ex1 = ExpandoObject()
ex1?Test<-"Hi"//Set Dynamic Property
ex1?Test //Get Dynamic
相关问题