在 Azure Functions 中将 F# 记录类型返回为 JSON [英] Return an F# record type as JSON in Azure Functions

查看:12
本文介绍了在 Azure Functions 中将 F# 记录类型返回为 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 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}

看起来这是由默认序列化程序引起的(将 F# 记录类型序列化为 JSON 在每个属性后包含@"字符).

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}

我怎样才能得到这个 JSON 响应?除了指定 DataMemberAttribute 还有其他方法吗?

How can I get this JSON response? Is there any other way apart from specifying DataMemberAttribute?

谢谢

推荐答案

我不认为你可以使用 JSON.Net(会很好),因为 AzureFunctions 基础结构似乎对 Data Contract Serializers

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 Functions 中将 F# 记录类型返回为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆