I am converting an existing application to consume JSON via POST from Bandwidth's V2 SDK for .NET. I'm not well-versed in either C# or JSON.
The previous version simply sent a JSON string like so:
{
"type" : "message-delivered",
"time" : "2016-09-14T18:20:16Z",
"description" : "Message delivered to carrier",
"to" : "+12345678902",
"message" : {
"id" : "14762070468292kw2fuqty55yp2b2",
"time" : "2016-09-14T18:20:16Z",
"to" : [
"+12345678902",
"+12345678903"
],
"from" : "+12345678901",
"text" : "",
"applicationId" : "93de2206-9669-4e07-948d-329f4b722ee2",
"owner" : "+12345678902",
"direction" : "in",
"segmentCount" : 1
}
}
And I could add it to my database like so:
// POST api/values
public HttpStatusCode Post([FromBody] CallbackEvent callback)
{
recCallback.Add(new tblCallback { Type = response, MessageID = callback.Message.Id, Description = callback.Description, MessageTo = callback.To, SegmentCount = callback.Message.SegmentCount });
callbacks.SaveChanges();
}
In version 2, it is wrapping the JSON response in []
- an array. Although they are still only passing a single callback, they are making it an array for future purposes.
I don't know how to reference this array so I might iterate through it. The CallbackEvent
class is as follows:
// Catapult Api callback event
public class CallbackEvent
{
public CallbackEvent();
public CallbackEventType Type { get; set; }
public DateTime Time { get; set; }
public string Description { get; set; }
public string To { get; set; }
public int ErrorCode { get; set; }
public IncomingMessage Message { get; set; }
public string ReplyTo { get; set; }
public int SegmentCount { get; set; }
// Parse callback eevent data from JSON
public static CallbackEvent[] CreateFromJson(string json);
}
Any help would be appreciated.
All you should have to do is change the controller signature:
// POST api/values
public HttpStatusCode Post([FromBody] List<CallbackEvent> callback)
{
//...
}
the .net deserializer should make this trivial. And then loop through the list (preferably in a business layer of some sort):
// POST api/values
public HttpStatusCode Post([FromBody] List<CallbackEvent> callback)
{
foreach(var message in callback)
{
recCallback.Add(new tblCallback { Type = response, MessageID =
message.Message.Id, Description = message.Description, MessageTo =
message.To, SegmentCount = message.Message.SegmentCount });
}
callbacks.SaveChanges(); // <-- Not sure of the context for this, but appears to be a dbContext and should be saved when done with List<T>
}