gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:51:47 25 4
gpt4 key购买 nike

我正在玩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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com