【问题标题】:GoCardless Event Won't DeserialiseGoCardless 事件不会反序列化
【发布时间】:2017-07-31 10:43:26
【问题描述】:

我正在尝试实现新的 GoCardless API,但在处理 webhook 时遇到了问题。

我已经通过以下方式读取了对字符串的响应:

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

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

这给了我一个json响应如下:

"{\"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\":{}}]}"

根据文档,我应该可以这样做

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

但是,这总是给我一个空白对象,所有属性都设置为 null。

Event 类的源代码可以在这里找到:https://github.com/gocardless/gocardless-dotnet/blob/master/GoCardless/Resources/Event.cs

为什么这不会反序列化为对象?

【问题讨论】:

    标签: c# json asp.net-mvc json.net gocardless


    【解决方案1】:

    很确定 JSON 是一个事件数组。所以首先你需要一个根对象:

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

    现在反序列化为该类型:

    var events = JsonConvert.DeserializeObject<Root>(requestContent);
    

    【讨论】:

    • 我也想知道,但是当我尝试时我得到一个错误:"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List1[GoCardless.Resources.Event]' 因为该类型需要一个 JSON 数组(例如 [1,2,3 ]) 正确反序列化。`
    • 糟糕,我的错误 - 您需要一个根对象 - 已编辑。
    • 是的 - 这行得通!如果他们保持简单并为每个事件单独调用。
    • 当然简单的是有一个可以返回任意数量事件的调用,所以,像这样吗? :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多