问题
"I have create a Azure Function in this function I call an API that returns JSON. I want to parse this JSON to an object so I can use it in the function. I cannot not use Newton.JSON as the function seems not to know this. How can I parse the JSON?"
回答1:
In the Azure Function your first you need to add a reference to NewtonSoft.JSON. You can do this via "Newtonsoft.Json". Do not forget the quotes!!!
Than you can use the normal serialization via newtonsoft:
var response = await client.GetAsync("<url>");
var json = await response.Content.ReadAsStringAsync();
var o= JsonConvert.DeserializeObject<"Type">(json);
回答2:
Here is a complete Azure Function source code for serializing/deserializing objects using 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; }
}
Sample input (request body):
{
"Category": "Azure Functions",
"Action": "Run",
"Label": "Test"
}
Sample output:
"{\"Category\":\"Azure Functions\",\"Action\":\"Run\",\"Label\":\"Test\"}"
回答3:
You answer above is returning a string and not JSON. I would suggest that you modify your answer as follows:
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);
}
This will return the Sample output without the JSON escapes:
{"Category":"Azure Functions","Action":"Run","Label":"Test"}
回答4:
As for .Net Core 2 :
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
and then you can deserialize it:
dynamic jObject= JsonConvert.DeserializeObject(requestBody);
and to complete your answer (convert to object):
JToken jCategory = jObject;
var whatever = jCategory["yourkeyiteminjson"].ToObject<YourObjectType>();
i.e to show you how flexible it is:
Let's say for this Json input:
{"companyId": "123456","payments": [{"id": "31212"},{"id": "31212"},{"id": "3"}],"miFees": [{"id": "452"},{"id": "254"}]}
You can do as follow:
var companyId = jObject["companyId"].ToString();
var payments = jCategory["payments"].ToObject<List<PaymentTransaction>>();
来源:https://stackoverflow.com/questions/38094170/how-can-i-parse-json-in-a-azure-function