如何从Azure功能返回JSON

xam*_*per 29 c# json azure azure-functions

我正在玩Azure功能.但是,我觉得我很难接受一些非常简单的事情.我想弄清楚如何返回一些基本的JSON.我不确定如何创建一些JSON并将其恢复到我的请求.

曾几何时,我会创建一个对象,填充其属性并对其进行序列化.所以,我开始沿着这条路走下去:

#r "Newtonsoft.Json"

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"Running Function");    
    try {      
      log.Info($"Function ran");

      var myJSON = GetJson();

      // I want myJSON to look like:
      // {
      //   firstName:'John',
      //   lastName: 'Doe',
      //   orders: [
      //     { id:1, description:'...' },
      //     ...
      //   ]
      // }
      return ?;
    } catch (Exception ex) {
        // TODO: Return/log exception
        return null;
    }
}

public static ? GetJson() 
{
  var person = new Person();
  person.FirstName = "John";
  person.LastName = "Doe";

  person.Orders = new List<Order>();
  person.Orders.Add(new Order() { Id=1, Description="..." });

  ?
}

public class Person 
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public List<Order> Orders { get; set; }
}

public class Order
{
  public int Id { get; set; }
  public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是,我现在完全停留在序列化和返回过程中.我想我习惯在ASP.NET MVC中返回JSON,其中一切都是Action

Lev*_*ler 28

这是一个Azure函数的完整示例,它返回格式正确的JSON对象而不是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")
    };
}
Run Code Online (Sandbox Code Playgroud)

在浏览器中导航到端点,您将看到:

{
  "name": "thomas",
  "location": "Denver"
}
Run Code Online (Sandbox Code Playgroud)


Bjo*_*pen 27

最简单的方法也许是

public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/jsontestapi")] HttpRequest req,
    ILogger log)
{
    return new JsonResult(resultObject);
}
Run Code Online (Sandbox Code Playgroud)

将内容类型设置为application/json并在响应正文中返回 json。


han*_*ker 14

你可以req

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
Run Code Online (Sandbox Code Playgroud)

并使用创建响应

return req.CreateResponse(HttpStatusCode.OK, json, "application/json");
Run Code Online (Sandbox Code Playgroud)

或装配中的任何其他重载System.Web.Http.

有关docs.microsoft.com的更多信息

  • 我更喜欢使用:`req.CreateResponse(HttpStatusCode.OK,json,JsonMediaTypeFormatter.DefaultMediaType);`.我认为它比`application/json`字符串更安全. (5认同)

juu*_*nas 5

JSON非常简单,Newtonsoft.Json库是一个特例.您可以通过在脚本文件的顶部添加它来包含它:

#r "Newtonsoft.Json"

using Newtonsoft.Json;
Run Code Online (Sandbox Code Playgroud)

然后你的功能变成:

public static string GetJson() 
{
  var person = new Person();
  person.FirstName = "John";
  person.LastName = "Doe";

  person.Orders = new List<Order>();
  person.Orders.Add(new Order() { Id=1, Description="..." });

  return JsonConvert.SerializeObject(person);
}
Run Code Online (Sandbox Code Playgroud)


Dim*_*a G 5

它看起来像这可以通过使用"应用/ JSON的"媒体类型,而无需显式序列化只是实现PersonNewtonsoft.Json.

以下是Chrome的完整工作示例:

{"FirstName":"John","LastName":"Doe","Orders":[{"Id":1,"Description":"..."}]}
Run Code Online (Sandbox Code Playgroud)

代码如下:

[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<Order>();
        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<Order> Orders { get; set; }
    }

    public class Order
    {
        public int Id { get; set; }
        public string Description { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)