我正在玩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
答案 0 :(得分: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")
};
}
在浏览器中导航到端点,您将看到:
{
"name": "thomas",
"location": "Denver"
}
答案 1 :(得分:14)
您可以从
获取req
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
并使用
创建响应return req.CreateResponse(HttpStatusCode.OK, json, "application/json");
或程序集System.Web.Http
中的任何其他重载。
答案 2 :(得分:5)
JSON很简单,Newtonsoft.Json库是special case。您可以通过在脚本文件的顶部添加它来包含它:
#r "Newtonsoft.Json"
using Newtonsoft.Json;
然后你的功能变为:
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);
}
答案 3 :(得分:5)
看起来这可以通过使用“application / json”媒体类型来实现,而无需使用Person
显式序列化Newtonsoft.Json
。
以下是Chrome的完整工作示例:
{"FirstName":"John","LastName":"Doe","Orders":[{"Id":1,"Description":"..."}]}
代码如下:
[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; }
}
答案 4 :(得分:2)
您可以将方法签名更改为:
public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
它将允许返回JSON数据。
答案 5 :(得分:1)
我有一个类似的问题,这似乎是最受欢迎的帖子,没有答案。在确定了下面的节点后,下面应该是什么节点,并准确地给出你所追求的内容。其他示例仍然返回一个字符串表示,这将返回JSON。
请记住使用System.Text声明;并且还添加:
return JsonConvert.SerializeObject(person);
按照Juunas的回应,到GetJson函数。
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(GetJson(), Encoding.UTF8, "application/json")
};
答案 6 :(得分:0)
最简单的方法也许是
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/jsontestapi")] HttpRequest req,
ILogger log)
{
return new JsonResult(resultObject);
}
将内容类型设置为application/json
并在响应正文中返回json。