Return F # record type as JSON in Azure Functions

I am creating a simple azure function in F #. At the end, I return the record type as JSON. I am doing something like this:

let y = {Gender = "Woman"; Frequency = 17; Percentage = 100.0}
req.CreateResponse(HttpStatusCode.OK, y);

When I call a function from Postman, I get this JSON {"Gender@":"Woman","Frequency@":17,"Percentage@":100}

This seems to be caused by the default serializer ( F # record type serialization for JSON includes the "@" character after each property ).

Then I tried using Newtonsoft.Json. Now the code is as follows:

req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(y));

But now I get this using the postman:

"{\"Gender\":\"Woman\",\"Frequency\":17,\"Percentage\":100}"

I want to get this answer: {"Gender":"Woman","Frequency":17,"Percentage":100}

How can I get a JSON response? Is there any other way besides the indication DataMemberAttribute?

thank

+4
source share
3

, JSON.Net( ), AzureFunctions .

F # JSON "@" , , clunkier .

, -

#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
} 
+1

100%, , , , , . , ( ):

let response = sprintf "%s" JsonConvert.SerializeObject(y)
req.CreateResponse(HttpStatusCode.OK, response)
0

!

req.CreateResponse(), JsonMediaTypeFormatter . ContractResolver , Json.Net.

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

return req.CreateResponse(HttpStatusCode.OK, { Foo = "Bar" }, jsonFormatter)
0
source

Source: https://habr.com/ru/post/1673607/


All Articles