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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With