如何从Azure函数返回JSON
本文关键字:返回 JSON 函数 Azure | 更新日期: 2023-09-27 18:02:25
我正在玩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; }
}
但是,我现在完全被序列化和返回过程卡住了。我想我已经习惯了在ASP中返回JSON。. NET MVC,一切都是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"
}
最简单的方法可能是
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/jsontestapi")] HttpRequest req,
ILogger log)
{
return new JsonResult(resultObject);
}
将内容类型设置为application/json
,并在响应体中返回json。
您可以从
获取req
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
并使用
创建响应return req.CreateResponse(HttpStatusCode.OK, json, "application/json");
或汇编System.Web.Http
中的任何其他过载。
关于learn.microsoft.com的更多信息
看起来这可以通过使用"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; }
}
JSON非常简单,Newtonsoft。Json库是一个特例。您可以通过在脚本文件的顶部添加以下内容来包含它:
#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);
}
您可以将方法签名更改为:
public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
我有一个类似的问题,这似乎是最受欢迎的帖子没有答案。在确定了节点的作用之后,下面的代码应该可以工作,并为您提供您所需要的东西。其他示例仍然返回字符串表示形式,而这将返回JSON。
请记住声明using System.Text;还要加上:
return JsonConvert.SerializeObject(person);
到GetJson函数。
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(GetJson(), Encoding.UTF8, "application/json")
};
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static IActionResult Run(HttpRequest req, ILogger log)
{
(string name, string surname) = ("James", "Ozzy");
return new ObjectResult(new { name, surname }) ;
}
您可以创建所有者响应:
var response = new HttpResponseMessage(HttpStatusCode.OK) {
Content = json
};
return new ObjectResult(response);
如果您既不使用Newtonsoft.Json
也不使用System.Web.Http
(如本答案)
var msg = new Msg("Hello, World");
var response = req.CreateResponse(HttpStatusCode.OK);
response.WriteAsJsonAsync(msg);
return response;