Creating a specific JSON format

I am trying to create a JSON request to send to the GetResponse email service to add a contact to the email campaign.

The format I'm trying to achieve is 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 a JSON string in C # I created this setting

 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 it like this

 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 as expected

 {"campaign":"my_test_campaign","action":"standard","name":"Test Name","email":" test@example.com ","cycle_day":0,"ip":"10.1.0.5"} 

I do not know how to correctly add the API_KEY line to the beginning.

How can I change this to add API_KEY to it forward without a property name attached to it, ideally using JavaScriptSerializer() ?

+6
source share
2 answers

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

 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); 
+4
source

The documentation shows that they wrap the JSON object in a proprietary way. JSON needs to start with '{', not '['. I would try something like this:

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

Source: https://habr.com/ru/post/953372/


All Articles