System.Cats.Lol System.Cats.Lol - 8 months ago 111
C# Question

Serialize enum as string in JSON returned from Azure Function

Is there a way to configure how Azure Functions serializes an object into JSON for the return value? I would like to use strings rather than ints for enum values.

For instance, given this code:-

public enum Sauce
{
None,
Hot
}

public class Dish
{
[JsonConverter(typeof(StringEnumConverter))]
public Sauce Sauce;
}

public static class MyFunction
{
[FunctionName("MakeDinner")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
var dish = new Dish() { Sauce = Sauce.Hot };
return req.CreateResponse(HttpStatusCode.OK, dish, "application/json");
}
}


The function returns:-

{
"Sauce": 1
}


How can I make it return the below?

{
"Sauce": "Hot"
}


I've tried returning a string instead of an object, but the result contains
\"
escapes; I want a JSON result, not an escaped string representation of a JSON object.

I know that in standard
ASP.NET
I can use the config to set serialization options. Is this even possible in Functions, or should I convert all my Enums to string constants?

Answer Source

Based on my test, I found the default version of the Newtonsoft.Json(installed when you created the azure function project) is 10.0.2. By using this version of the Newtonsoft.Json, it will auto replace the enum string name with the number.

Here is a workaround, I suggest you could open the Nuget Package install the Newtonsoft.Json 9.0.1, then it will work well.

More details, you could refer to below image:

enter image description here

Result:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download