Reputation: 855
I am importing a webhook to a SQL Database via Azure Functions.
When I import using
{
"remote_address": "1234",
}
This works.
But when I import using
{
"transaction": {
"remote_address": "1234",
}
}
It doesn't work.
The Azure Function code I have is:
using System.Net;
using Dapper;
using System.Data.SqlClient;
using System.Configuration;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
var successful =true;
try
{
var cnnString = ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString;
using(var connection = new SqlConnection(cnnString))
{
connection.Open();
var rLog = await req.Content.ReadAsAsync<LogRequest>();
// insert a log to the database
connection.Execute("INSERT INTO [dbo].[TABLE] ([COLUMN]) VALUES (@remote_address)", rLog);
log.Info("Log added to database successfully!");
}
}
catch
{
successful=false;
}
return !successful
? req.CreateResponse(HttpStatusCode.BadRequest, "Unable to process your request!")
: req.CreateResponse(HttpStatusCode.OK, "Data saved successfully!");
}
public class LogRequest
{
public int Id{get;set;}
public string remote_address{get;set;}
}
How can I get the Nested JSON Object?
Upvotes: 0
Views: 115
Reputation: 2726
To expand on Mikhail's good answer, depending on your requirements it's sometimes easiest to use JObject/dynamic
.
var jobjectBody = await req.Content.ReadAsAsync<JObject>();
dynamic dynamicBody = jobjectBody;
string remote_address = dynamicBody.transaction.remote_address;
Upvotes: 1
Reputation: 35124
Basically you can nest your C# classes so that they correspond to JSON structure:
public class Transaction
{
public string remote_address { get; set; }
}
public class LogRequest
{
public Transaction transaction { get; set; }
}
Upvotes: 2