How do I return JSON from an Azure Function

前端 未结 7 1420
逝去的感伤
逝去的感伤 2021-02-06 20:43

I am playing with Azure Functions. However, I feel like I\'m stumped on something pretty simple. I\'m trying to figure out how to return some basic JSON. I\'m not sure how to cr

7条回答
  •  死守一世寂寞
    2021-02-06 21:22

    It looks like this can be achieved just by using the "application/json" media type, without the need to explicitly serialize Person with Newtonsoft.Json.

    Here is the full working sample that results in Chrome as:

    {"FirstName":"John","LastName":"Doe","Orders":[{"Id":1,"Description":"..."}]}
    

    The code is given as below:

    [FunctionName("StackOverflowReturnJson")]
        public static HttpResponseMessage Run([HttpTrigger("get", "post", Route = "StackOverflowReturnJson")]HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"Running Function");
            try
            {
                log.Info($"Function ran");
    
                var myJSON = GetJson();  // Note: this actually returns an instance of 'Person' 
    
                // I want myJSON to look like:
                // {
                //   firstName:'John',
                //   lastName: 'Doe',
                //   orders: [
                //     { id:1, description:'...' },
                //     ...
                //   ]
                // }
                var response = req.CreateResponse(HttpStatusCode.OK, myJSON, JsonMediaTypeFormatter.DefaultMediaType); // DefaultMediaType = "application/json" does the 'trick'
                return response;
            }
            catch (Exception ex)
            {
                // TODO: Return/log exception
                return null;
            }
        }
    
        public static Person GetJson()
        {
            var person = new Person();
            person.FirstName = "John";
            person.LastName = "Doe";
    
            person.Orders = new List();
            person.Orders.Add(new Order() { Id = 1, Description = "..." });
    
            return person;
        }
    
        public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public List Orders { get; set; }
        }
    
        public class Order
        {
            public int Id { get; set; }
            public string Description { get; set; }
        }
    

提交回复
热议问题