简体   繁体   中英

How to retrieve nested json objects in C#?

Stripe Transfer JSON

I'm trying to get all charge IDs associated with a transfer.

var json = new StreamReader(context.Request.InputStream).ReadToEnd();

var stripeEvent = StripeEventUtility.ParseEvent(json);

StripeTransfer stripeTransfer;
switch (stripeEvent.Type)
{
    case "transfer.created":
        stripeTransfer = Stripe.Mapper<StripeTransfer>.MapFromJson(stripeEvent.Data.Object.ToString());
        var transferId = stripeTransfer.Id;
        stripeTransfer = _stripeManager.GetTransfer(transferId);

        foreach (var charge in stripeEvent.Data.Object["transactions"])
        {

        }

        _stripeManager.ProcessTransfer(stripeTransfer);
        break;

In visual studio's immediate window, stripeEvent.Data.Object["transactions"] shows the data I want so I know that the json is getting sucked in properly. Those transactions are a collection of charges, they match my .net StripeCharge object. I'm having trouble figuring out how to iterate through the transactions...all I really need is the ID for each. Would like to see "transactions" as a C# IEnumerable object.

(the json in question is linked at the top of this post) let me know if more info is needed.

I've found the specific item is under ["transactions"]["data"][0]["id"] but there may be more than one so, still working on how to get them out and cast them...think I'm close but it seems like there should be a more elegant way of doing it.

EDIT,

Thanks Andrew, so even though I have all of the charge data, it is incoming data. So what I'll be doing is using the event to just get the id and then make the call to get the charge object from my own end to prevent any event spoofs. So that means I don't have to worry about casting at this point. Here is my solution, feel free to advise if there is a better way to do it

for (int i = 0; i < Int32.Parse(stripeEvent.Data.Object["transactions"]["total_count"].ToString()); i++)
{
     string chargeId = stripeEvent.Data.Object["transactions"]["data"][i]["id"].ToString();
     // do stuff with it
}

just for completeness: Data under transactions looks like an array so should be able to index into them..

If you need to access to any other fields in the future you could construct c# objects but given the webhook 3rd party dance you are already doing probably not worth it as you only need id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM