How can I Parse Json in a Azure Function How can I Parse Json in a Azure Function json json

How can I Parse Json in a Azure Function


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\"}"


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"}


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>>();