gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:09:50 24 4
gpt4 key购买 nike

我正在使用 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

最佳答案

我没有使用该特定库的经验,但如果结果只是正常的 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 解析,因为这样你就可以替换所有动态不安全的 ?通过类型检查进行访问!

关于f# - 如何使用 F# 访问 ExpandoObject 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com