Why do Azure Functions not support System.Text.Json
and everyone uses newtonsoft in examples?
Is it possible to use System.Text.Json in Azure functions?
public static class FanyFunctionName
{
[FunctionName("FanyFunctionName")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
HttpRequest req,
ILogger log)
{
try
{
// Read the request body and deserialize it
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var eventObject = JsonConvert.DeserializeObject<Event>(requestBody);
// Log the event type and other necessary information in one log statement
return new OkResult();
}
catch (Exception ex)
{
log.LogError(ex, "Error processing event");
return new BadRequestObjectResult("Error processing event");
}
}
}
2
Answers
Yes,
System.Text.Json
can be used in Azure Functions and WebJobs without any problems.As I already mentioned in the Comments, it is not like
system.json.Text
doesn’t support but Azure function usesNewtonsoft.Json
by default.When we create Function App, by default,
requestBody
generates code withJsonConvert.DeserializeObject
fromNewtonsoft.Json
.Code with
Newtonsoft.Json
:When we use
System.Text.Json
,JsonConvert
is not allowed in the Function,I tried with
JsonSerializer.Deserialize<JsonElement>
and got the below error.I have modified the code as below, Now Iam able to access the Function.
Using
System.Text.Json
:Output: