skip to Main Content

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


  1. Yes, System.Text.Json can be used in Azure Functions and WebJobs without any problems.

    Login or Signup to reply.
  2. As I already mentioned in the Comments, it is not like system.json.Text doesn’t support but Azure function uses Newtonsoft.Json by default.

    When we create Function App, by default, requestBody generates code with JsonConvert.DeserializeObject from Newtonsoft.Json.

    Code with Newtonsoft.Json:

    using Newtonsoft.Json;
    
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;
    

    When we use System.Text.Json , JsonConvert is not allowed in the Function,

    enter image description here

    I tried with JsonSerializer.Deserialize<JsonElement> and got the below error.

    enter image description here

    I have modified the code as below, Now Iam able to access the Function.

    Using System.Text.Json :

    using System.Text.Json;
    
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    if (!string.IsNullOrEmpty(requestBody))
    {
        dynamic data = JsonSerializer.Deserialize<JsonElement>(requestBody);
        name = name ?? data.GetProperty("name").GetString();
    }
    

    Output:
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search