Search code examples
c#xamarinopayo

Xamarin/C# POST to RESTful api


Apologies if this is a stupid question, i've been thrown onto a project with very little prior C#/Xamarin knowledge and I've been banging my head against a wall with this for some time.

So...

I'm trying to make a post call to SagePay API (https://test.sagepay.com/documentation/#card-identifiers)

I've been accessing our API and i've accessed the other SagePay API fine,

what i'm having issues with is that this call is a 'nested' json (apologies for incorrect terminology)

How do I go about submitting a POST in this format

{
"cardDetails":
    {
        "cardholderName": "SAM JONES",
        "cardNumber": "4929000000006",
        "expiryDate": "0320",
        "securityCode": "123"
    }
}

Solution

  • You have your objects created in that link (json2csharp):

    public class CardDetails
    {
        public string cardholderName { get; set; }
        public string cardNumber { get; set; }
        public string expiryDate { get; set; }
        public string securityCode { get; set; }
    }
    
    public class RootObject
    {
        public CardDetails cardDetails { get; set; }
    }
    

    To serialize (JSON.Net):

    var cardIdentifier = new RootObject{
        cardDetails = new CardDetails{
            cardholderName = "EdSF", 
            cardNumber = "4111111111111111", 
            expiryDate = "0320", 
            securityCode = "123"
        }
    };
    
    
    Console.WriteLine(JsonConvert.SerializeObject(cardIdentifier));
    

    Result:

    {
      "cardDetails": {
        "cardholderName": "EdSF",
        "cardNumber": "4111111111111111",
        "expiryDate": "0320",
        "securityCode": "123"
      }
    }
    

    Hth....