作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在玩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/
我是一名优秀的程序员,十分优秀!