we have the following structure.
public class Foo {
[JsonPropertyName("x")]
public string Prop1 { get; set; }
[JsonPropertyName("y")]
public string Prop2 { get; set; }
[JsonPropertyName("z")]
public string Prop3 { get; set; }
}
[FunctionName("Func")]
public static Foo Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log
)
{
Foo foo = new();
foo.Prop1 = "Value 1";
foo.Prop2 = "Value 2";
foo.Prop3 = "Value 3";
return foo;
}
The return of the function will be
{
"Prop1" : "Value 1",
"Prop2" : "Value 2",
"Prop3" : "Value 3",
}
instead of
{
"x" : "Value 1",
"y" : "Value 2",
"z" : "Value 3",
}
I could serialize it myself and return the string. That works. But how can I get the correct resolved 'JsonPropertyName' annotations with direct return of the object?
(With Newtonsoft annotations the return also works. So it seems that somehow Newtonsoft will do there some stuff. We have no Newtonsoft in use in that project.)
I found a workaround in this article.
It seems that Azure Function does not respect the [JsonPropertyName]
attribute, but System.Text.Json
does.
[FunctionName("Func")]
public static Foo Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log
)
{
Foo foo = new();
foo.Prop1 = "Value 1";
foo.Prop2 = "Value 2";
foo.Prop3 = "Value 3";
var data = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(foo);
return new FileContentResult(data, "application/json");
}