Bor*_*vee 15 json azure azure-functions
"我在这个函数中创建了一个Azure函数,我调用了一个返回JSON的API.我想将这个JSON解析为一个对象,所以我可以在函数中使用它.我不能不使用Newton.JSON,因为函数似乎不知道这个.我怎么解析JSON?"
Tho*_*ena 39
这是一个完整的Azure Function源代码,用于使用JsonNet序列化/反序列化对象:
#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
dynamic body = await req.Content.ReadAsStringAsync();
var e = JsonConvert.DeserializeObject<EventData>(body as string);
return req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(e));
}
public class EventData
{
public string Category { get; set; }
public string Action { get; set; }
public string Label { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
样本输入(请求正文):
{
"Category": "Azure Functions",
"Action": "Run",
"Label": "Test"
}
Run Code Online (Sandbox Code Playgroud)
样本输出:
"{\"Category\":\"Azure Functions\",\"Action\":\"Run\",\"Label\":\"Test\"}"
Run Code Online (Sandbox Code Playgroud)
小智 5
你上面的回答是返回一个字符串而不是JSON.我建议你修改你的答案如下:
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
dynamic body = await req.Content.ReadAsStringAsync();
var e = JsonConvert.DeserializeObject<EventData>(body as string);
return req.CreateResponse(HttpStatusCode.OK, e);
}
Run Code Online (Sandbox Code Playgroud)
这将返回没有JSON转义的Sample输出:
{"Category":"Azure Functions","Action":"Run","Label":"Test"}
Run Code Online (Sandbox Code Playgroud)
小智 0
在 Azure 函数中,您首先需要添加对 NewtonSoft.JSON 的引用。您可以通过“Newtonsoft.Json”来完成此操作。不要忘记引号!
您可以通过 newtonsoft 使用正常的序列化:
var response = await client.GetAsync("<url>");
var json = await response.Content.ReadAsStringAsync();
var o= JsonConvert.DeserializeObject<"Type">(json);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19431 次 |
最近记录: |