3

I'm trying to implement the new GoCardless API, but I'm having trouble handling webhooks.

i've read the response to a string, by doing:

Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);

string requestContent = new StreamReader(req).ReadToEnd();

This gives me a json response as follows:

"{\"events\":[{\"id\":\"EV000SDG4B5WRP\",\"created_at\":\"2017-07-31T08:17:16.202Z\",\"resource_type\":\"mandates\",\"action\":\"cancelled\",\"links\":{\"mandate\":\"MD0002010AE1MV\"},\"details\":{\"origin\":\"api\",\"cause\":\"bank_account_closed\",\"description\":\"The customer's account was disabled at your request.\"},\"metadata\":{}}]}"

According to the docs, I should then be able to do

JsonConvert.DeserializeObject<GoCardless.Resources.Event>(requestContent);

However, this always gives me a blank object, with all properties set to null.

The source code to the Event class can be found here: https://github.com/gocardless/gocardless-dotnet/blob/master/GoCardless/Resources/Event.cs

Why will this not deserialize to the object?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gavin Coates
  • 1,366
  • 1
  • 20
  • 44

1 Answers1

4

Pretty sure that JSON is an array of events. So first you need a root object:

public class Root
{
    public List<GoCardless.Resources.Event> Events { get; set; }
}

Now deserialise into that type:

var events = JsonConvert.DeserializeObject<Root>(requestContent);
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • I wondered that too, but when I try that I get an error: `"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[GoCardless.Resources.Event]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.` – Gavin Coates Jul 31 '17 at 11:04
  • Oops, my error - you need a root object - have edited. – DavidG Jul 31 '17 at 11:06
  • yep - that works! If only they'd kept it simple and made a separate call for each event. – Gavin Coates Jul 31 '17 at 13:10
  • 1
    Surely simple would be to have a single call that could return any number of events, so, like this? :) – DavidG Jul 31 '17 at 13:11