I had to work with JSON recently to integrate the Payeezy gateway to our website. First time I used the dynamic type in C#. Below is the code I used to create the JSON:
dynamic payload = new
{
merchant_ref = "Payeezy Token test",
transaction_type = "purchase",
method = "token",
amount = amt,
currency_code = "USD",
token = new
{
token_type = "FDToken",
token_data = new
{
type = cardType,
value = transarmorTokenValue,
cardholder_name = cardHolder,
exp_date = expMonth+expYear
}
}
};
jsonString = JSONHelper.ToJSON(payload);
In order to parse the response JSON:
StreamReader responseStream = new StreamReader(webResponse.GetResponseStream());
responseString = responseStream.ReadToEnd();
var responseValues = JSONHelper.ToDictionaryStringObject(responseString);
int bankResponse = Convert.ToInt32(responseValues["bank_resp_code"]);
The JSONHelper class:
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public Dictionary<string, object> ToDictionaryStringObject(string s)
{
var json = new JavaScriptSerializer();
return json.Deserialize<Dictionary<string, object>>(s);
}
}
dynamic payload = new
{
merchant_ref = "Payeezy Token test",
transaction_type = "purchase",
method = "token",
amount = amt,
currency_code = "USD",
token = new
{
token_type = "FDToken",
token_data = new
{
type = cardType,
value = transarmorTokenValue,
cardholder_name = cardHolder,
exp_date = expMonth+expYear
}
}
};
jsonString = JSONHelper.ToJSON(payload);
In order to parse the response JSON:
StreamReader responseStream = new StreamReader(webResponse.GetResponseStream());
responseString = responseStream.ReadToEnd();
var responseValues = JSONHelper.ToDictionaryStringObject(responseString);
int bankResponse = Convert.ToInt32(responseValues["bank_resp_code"]);
The JSONHelper class:
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public Dictionary<string, object> ToDictionaryStringObject(string s)
{
var json = new JavaScriptSerializer();
return json.Deserialize<Dictionary<string, object>>(s);
}
}