在Azure函数中将F#记录类型返回为JSON [英] Return an F# record type as JSON in Azure Functions
问题描述
我正在F#中创建一个简单的Azure函数.最后,我将返回一个记录类型为JSON.我正在做这样的事情:
I'm creating a simple azure function in F#. At the end, I'm returning a record type as JSON. I'm doing something like this:
let y = {Gender = "Woman"; Frequency = 17; Percentage = 100.0}
req.CreateResponse(HttpStatusCode.OK, y);
当我从Postman调用函数时,我得到了这个JSON
{"Gender@":"Woman","Frequency@":17,"Percentage@":100}
When I call the function from Postman I'm getting this JSON
{"Gender@":"Woman","Frequency@":17,"Percentage@":100}
It looks like that this is caused by the default serializer (Serializing F# Record type to JSON includes '@' character after each property).
然后我尝试使用Newtonsoft.Json.现在,代码如下所示:
Then I tried to use Newtonsoft.Json. Now, the code looks like this:
req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(y));
但是现在我使用邮递员来获取它:
But now I'm getting this using postman:
"{\"Gender\":\"Woman\",\"Frequency\":17,\"Percentage\":100}"
我想得到这个回复:
{"Gender":"Woman","Frequency":17,"Percentage":100}
I'd like to get this response:
{"Gender":"Woman","Frequency":17,"Percentage":100}
如何获取此JSON响应?除了指定DataMemberAttribute
之外,还有其他方法吗?
How can I get this JSON response? Is there any other way apart from specifying DataMemberAttribute
?
谢谢
推荐答案
我认为您不能使用JSON.Net(这很好),因为数据契约序列化程序似乎对AzureFunctions基础结构
I don't think you can use JSON.Net (would be nice) because the AzureFunctions infrastructure seems to the Data Contract Serializers
我已经按照将F#记录类型序列化为JSON并将每个属性后的'@'字符序列化为如果比您希望的更笨重,它将对我有用.
I have just implemented the fix as per Serializing F# Record type to JSON includes '@' character after each property and it works for me if a bit clunkier than you may hope.
我也在努力解决这个问题,您使我朝着正确的方向前进-谢谢
I was also struggling to fix this and you got me going in the right direction - Thanks
#r "System.Runtime.Serialization"
open System.Runtime.Serialization
[<DataContract>]
type SearchItem = {
[<field: DataMember(Name="Gender")>]
Gender: string
[<field: DataMember(Name="Frequency")>]
Frequency: int
[<field: DataMember(Name="Percentage")>]
Percentage: float
}
这篇关于在Azure函数中将F#记录类型返回为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!