Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an F# record type as JSON in Azure Functions

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);

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).

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

I'd like to get this response: {"Gender":"Woman","Frequency":17,"Percentage":100}

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

Thanks

like image 458
vgaltes Avatar asked Oct 18 '22 14:10

vgaltes


1 Answers

I found a super simple way to fix this!

There is an overload to req.CreateResponse() that takes a JsonMediaTypeFormatter as a 3rd parameter. This allows us to set the ContractResolver to one provided by Json.Net.

let jsonFormatter = System.Net.Http.Formatting.JsonMediaTypeFormatter()
jsonFormatter.SerializerSettings.ContractResolver <- Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()

return req.CreateResponse(HttpStatusCode.OK, { Foo = "Bar" }, jsonFormatter)
like image 129
mikesigs Avatar answered Nov 15 '22 08:11

mikesigs