user3010678
user3010678

Reputation: 142

C# how to return key/value json response without using dynamic?

I am working on an Azure Function app and want to have a bunch of methods that return a simple, strongly typed response which serializes to json in a simple way without using OkObjectResult due to it having too many extra properties that I don't need.

Example of desired output, where "Value" can become a complex type serialized to json:

{
    FooBar : Value
}

This is pretty easily achieved by using 'dynamic' keyword.

    [Function("CreateFooBar")]
    public async Task<dynamic> CreateFooBar([HttpTrigger(AuthorizationLevel.Anonymous, "post")]
        HttpRequestData req,
        FunctionContext executionContext)
    {
         return new
         {
             FooBar = "Value"
         }
    }

However, I don't want to have dynamic everywhere in my code. How can I make the below code actually work so it serializes using a key/value style mechanism? The JsonSerialization and ISerialization doesn't seem to provide an interface for this?

    public class OkResultWithValue 
    {
        public OkResultWithValue(string key,object value)
        {
           _key= key;
        }

        private string _key;
        public object  Value { get;  set ; }
    }

    [Function("CreateFooBar")]
    public async Task<OkResultWithValue> CreateFooBar([HttpTrigger(AuthorizationLevel.Anonymous, "post")]
        HttpRequestData req,
        FunctionContext executionContext)
    {
        object value = DoSomeThing();
        return new OkResultWithValue("FooBar",value)
    }

Now I can have all my Azure Functions return a strongly typed OkResultWithValue like this:

Upvotes: 0

Views: 204

Answers (1)

Blindy
Blindy

Reputation: 67362

You can achieve the same with object instead:

[Function("CreateFooBar")]
public async Task<object> CreateFooBar([HttpTrigger(AuthorizationLevel.Anonymous, "post")]
    HttpRequestData req,
    FunctionContext executionContext)
{
     return new
     {
         FooBar = "Value"
     }
}

Upvotes: 1

Related Questions