Kirk
Kirk

Reputation: 16265

Creating a specific JSON format

I'm attempting to create a JSON request to send to email service GetResponse to add a contact to a mail campaign.

The format I'm trying to achieve is for add_contact

[
    "API_KEY",
    {
        "campaign"  : "CAMPAIGN_ID",
        "action"    : "action_value",
        "name"      : "name_value",
        "email"     : "email_value",
        "cycle_day" : cycle_day_value,
        "ip"        : "ip_value",
        "customs"   : [
            {
                "name"      : "name_1_value",
                "content"   : "content_1_value"
            },
            {
                "name"      : "name_2_value",
                "content"   : "content_2_value"
            }
        ]
    }
]

Following How to create JSON string in C# I contructed this setup

private class AddContactRequest
{
    public string campaign { get; set; }
    public string action { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public int cycle_day { get; set; }
    public string ip { get; set; }
}

And filled this like so

AddContactRequest add = new AddContactRequest();
add.campaign = campaignID;
add.action = action
add.name = contact_name;
add.email = email;
add.cycle_day = cycle_day;
add.ip = ip_value;

string json = new JavaScriptSerializer().Serialize(add);

Here json is as expected

{"campaign":"my_test_campaign","action":"standard","name":"Test Name","email":"[email protected]","cycle_day":0,"ip":"10.1.0.5"}

What I don't know is how to properly add the API_KEY string to the front of it.

How can I alter this to add the API_KEY to the front of it without a property name attached to it, ideally using JavaScriptSerializer()?

Upvotes: 6

Views: 243

Answers (2)

user2756222
user2756222

Reputation: 11

From the documentation, it looks like they're wrapping the JSON object in a proprietary fashion. JSON needs to start with a '{', not a '['. I would try something like this:

string json = new JavaScriptSerializer().Serialize(SerializedThingy);
string req = "[ \"API_KEY\", " + json + " ]";

Upvotes: 1

bluetoft
bluetoft

Reputation: 5443

What you need to do is create a collection of type object and pass "API_KEY" as the first entry and your add object as the second entry.

AddContactRequest add = new AddContactRequest();
add.campaign = campaignID;
add.action = action
add.name = contact_name;
add.email = email;
add.cycle_day = cycle_day;
add.ip = ip_value;

List<object> SerializedThingy = new List<object>
{
   "API_KEY",
   add
};

string json = new JavaScriptSerializer().Serialize(SerializedThingy);

Upvotes: 4

Related Questions