3

I'm returning an object from my Azure function using OkObjectResult, but the object's JSON still contains properties I've marked JsonIgnore. Why is that, and how can I fix it?

Details:

I have this class:

using System.Text.Json.Serialization;
// ...
public class Example
{
    public string A { get; set; }
    public string B { get; set; }
    [JsonIgnore]
    public string C { get; set; }
}

When returning from an Azure function, if I do:

var result = new Example() { A = "Ayy", B = "Bee", C = "See" };
return new OkObjectResult(result);

...the JSON returned is (I've added formatting):

{
    a: "Ayy",
    b: "Bee",
    c: "See"
}

Notice that the JsonIgnore attribute didn't take effect, the JSON has a c property.

But if I serialize explicitly:

var result = new Example() { A = "Ayy", B = "Bee", C = "See" };
return new OkObjectResult(
    JsonSerializer.Serialize(
        result,
        new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase}
    )
);

...c is left out as desired:

{
    a: "Ayy",
    b: "Bee"
}

Why isn't the property being left out when I give the object to OkObjectResult directly, and how do I fix it?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875

1 Answers1

4

The problem is the class code uses the wrong JsonIgnore attribute because of this:

using System.Text.Json.Serialization;

As of this writing, Azure functions (still) use Newtonsoft.Json by default,1 so the property is marked with the wrong attribute, and the serializer doesn't know to leave it out.

To fix it, import Newtonsoft.Json instead:

using Newtonsoft.Json; // <====================
// ...
public class Example
{
    public string A { get; set; }
    public string B { get; set; }
    [JsonIgnore]
    public string C { get; set; }
}

1 If you use Visual Studio's Add... > Azure Function, the template it creates includes the import of Newtonsoft.Json, which is the only reason I realized this. See also this related issue (thanks for that, Eldar!).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    It pisses me off when the technologies are not aligned. The related [issue](https://github.com/Azure/azure-functions-host/issues/5469) – Eldar Mar 07 '23 at 12:47
  • @Eldar - Yeah, this cost me a good 45 minutes (plus another 15 to try to save others the time). *"Function v3 uses System.Text.Json as input serializer and Newtonsoft.Json as output serializer."* OMG! :-) (Edit: Oh, wait, Microsoft said that wasn't correct, that it always uses NewtonSoft.) – T.J. Crowder Mar 07 '23 at 12:48