如何在 Azure 函数中解析 Json

How can I Parse Json in a Azure Function

“我在这个函数中创建了一个 Azure 函数,我调用了一个 returns JSON 的 API。我想将这个 JSON 解析为一个对象,所以我可以在函数中使用它。我不能不使用 Newton.JSON 因为函数似乎不知道这一点。 我如何解析 JSON?"

在 Azure 函数中,您首先需要添加对 NewtonSoft.JSON 的引用。您可以通过 "Newtonsoft.Json" 执行此操作。不要忘记引号!!!

你可以通过 newtonsoft 使用正常的序列化:

var response = await client.GetAsync("<url>");
var json = await response.Content.ReadAsStringAsync();
var o= JsonConvert.DeserializeObject<"Type">(json);

这是使用 JsonNet 的 serializing/deserializing 对象的完整 Azure 函数源代码:

#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; }
}

示例输入(请求正文):

{
    "Category": "Azure Functions",
    "Action": "Run",
    "Label": "Test"
}

示例输出:

"{\"Category\":\"Azure Functions\",\"Action\":\"Run\",\"Label\":\"Test\"}"

您上面的回答是 return 字符串而不是 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);
}

这将 return 没有 JSON 转义的样本输出:

{"Category":"Azure Functions","Action":"Run","Label":"Test"}

至于 .Net Core 2:

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

然后你可以反序列化它:

dynamic jObject= JsonConvert.DeserializeObject(requestBody);

并完成您的回答(转换为对象):

JToken jCategory = jObject;
var whatever = jCategory["yourkeyiteminjson"].ToObject<YourObjectType>();

即向您展示它的灵活性:

假设这个 Json 输入:

{"companyId": "123456","payments": [{"id": "31212"},{"id": "31212"},{"id": "3"}],"miFees": [{"id": "452"},{"id": "254"}]}

您可以进行如下操作:

var companyId = jObject["companyId"].ToString();
var payments = jCategory["payments"].ToObject<List<PaymentTransaction>>();