0

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.)

dbc
  • 104,963
  • 20
  • 228
  • 340
mburm
  • 1,417
  • 2
  • 17
  • 37
  • The `JsonPropertyName` specifies the property name that is present in the JSON when serializing and deserializing. In `System.Text.Json.Serialization` ,the attribute is not used outside serialization. If you are not serializing the result to JSON your object names will be what they are as defined. More details on the attibute: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonpropertynameattribute?view=net-7.0 – Nope Mar 15 '23 at 15:01
  • Ok, good to know. Is there another way I can use something in the `System.Text.Json` context to return the object and define the names in the model or have I to use either the serialization or Newtonsoft? – mburm Mar 15 '23 at 15:04
  • That "stuff" Newtonsoft does is serializing the result, hence it would use the attribute values as well. Either serialize the result or return an object with the desired property names to begin with. – Nope Mar 15 '23 at 15:22
  • 1
    Even if *We have no Newtonsoft in use in that project* it looks like Azure Core uses Json.NET not System.Text.Json. See [Newtonsoft.Json support for Azure Core shared client library for .NET](https://learn.microsoft.com/en-us/dotnet/api/overview/azure/microsoft.core.newtonsoftjson-readme?view=azure-dotnet): *The Azure.Core package contains types shared by all Azure SDK client libraries. This library contains converters dependent on the Newtonsoft.Json package for use with Azure.Core.* So if you don't want a dependency on Json.NET I'd suggest using a DTO along the lines of Serge's answer. – dbc Mar 15 '23 at 16:20

1 Answers1

0

You can use this code for example

public static ActionResult Run(....
{
    return new {
    x = "Value 1",
    y = "Value 2",
    z = "Value 3"
    };
}

}
Serge
  • 40,935
  • 4
  • 18
  • 45