c# - 如何从 Azure 函数返回 JSON

标签 c# json azure azure-functions

我正在玩Azure Functions 。然而,我觉得我被一些非常简单的事情难住了。我正在尝试弄清楚如何返回一些基本的 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; }
}

但是,我现在完全陷入了序列化和返回过程。我想我已经习惯在 ASP.NET MVC 中返回 JSON,其中一切都是 Action

最佳答案

以下是 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")
    };
}

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

{
  "name": "thomas",
  "location": "Denver"
}

关于c# - 如何从 Azure 函数返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38943858/

相关文章:

c# - 通过 IronPython 在 C# 中使用 NLTK

c# - 如何删除 FileSystemWatcher 对象的特定实例

azure - 如何确保同一时间只允许运行一个 Azure Functions 事件网格触发器实例?

azure - 为什么需要额外的子网用于应用服务的 VNET 集成

c# - Azure表存储: "Parameter count mismatch" storing array/list/IEnumerable

c# - 当我们指定了类的访问说明符时,是否有任何约束来指定类成员的访问说明符?

c# - 在另一个线程中动态添加控件到 WinForms

json - 具有 50 个 CIDR IP 的安全组的 Cloudformation 模板(JSON)(入口)

json - 如何在json中找到响应对象的数量

javascript - 如何创建一个 json 对象并附加到 node.js 中的实际响应中