How do I return JSON from an Azure Function

前端 未结 7 1422
逝去的感伤
逝去的感伤 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:42

    Here's a full example of an Azure function returning a properly formatted JSON object instead of XML:

    #r "Newtonsoft.Json"
    using System.Net;
    using Newtonsoft.Json;
    using System.Text;
    
    public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
    {
        var myObj = new {name = "thomas", location = "Denver"};
        var jsonToReturn = JsonConvert.SerializeObject(myObj);
    
        return new HttpResponseMessage(HttpStatusCode.OK) {
            Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
        };
    }
    

    Navigate to the endpoint in a browser and you will see:

    {
      "name": "thomas",
      "location": "Denver"
    }
    
    0 讨论(0)
提交回复
热议问题