How can I Parse Json in a Azure Function

Boris Pluimvee picture Boris Pluimvee · Jun 29, 2016 · Viewed 24.5k times · Source

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

Answer

Thomas C. G. de Vilhena picture Thomas C. G. de Vilhena · Sep 23, 2016

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