braintree / braintree_dotnet

Braintree .NET library
https://developer.paypal.com/braintree/docs/start/overview
MIT License
136 stars 73 forks source link

De/Serialization of WebHookNotification #48

Closed ADringer closed 7 years ago

ADringer commented 7 years ago

Hi,

I'm currently serializing a WebhookNotification to so I can add the message to my Azure Service Bus. However it appears that the kind property is not serialized correctly, it comes out as blank:

{ "Kind":{}, "Subscription" :null, ....... }

Is it possible to allow the Kind value to be serialized so that I can have a full copy of the notification stored?

I'm using Json.Net's JsonConvert.SerializeObject method to serialize the object.

And then subsequently can you allow the json string to be deserialized back to the WebhookNotification object?

Thanks

patrickmichalina commented 7 years ago

I have been struggling to figure out why the webhooks are failing when consuming them via a normal Web API POST endpoint. I found that I need to remove an additional "\" in a "\n" otherwise the parsing fails due to an "illegal character" error.

EvanHahn commented 7 years ago

JSON (de)serialization isn’t something we’re planning on adding. We don’t want to get in the business of adding serialization functionality. Since the part of the Braintree API that this SDK speaks with is XML-based, we’re not going to introduce other encodings for the time being.

You can use Json.NET’s JsonConverter functionality to serialize WebHookNotificiations yourself. Here’s a simple example:

private class WebHookNotificationConverter : JsonConverter
{
  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
    JToken t = JToken.FromObject(value);
    JObject o = (JObject)t;

    WebhookNotification note = (WebhookNotification)value;

    JObject webhookKind = new JObject();
    webhookKind.AddFirst(new JProperty("Name", note.Kind.ToString()));
    o.Remove("Kind");
    o.Add(new JProperty("Kind", webhookKind));

    o.WriteTo(writer);
  }

  public override bool CanRead
  {
    get { return false; }
  }

  public override bool CanConvert(Type objectType)
  {
    return true;
  }
}

string json = JsonConvert.SerializeObject(notification, Formatting.Indented, new WebHookNotificationConverter());

Deserialization is a bit trickier. Since we don’t (and have no plans to) expose public setters for these model objects, it would be tough sledding to write a deserializer for WebhookNotification, or any object in this SDK. However, since this SDK supports XML out of the box, you can always use the built in XML encoding and decoding functionality.

I realize this isn’t a great answer and doesn’t help your immediate use case, but I hope this gets you at least part of the way there. Thanks for opening an issue!