创建特定的JSON格式

时间:2013-09-07 03:32:14

标签: c# json

我正在尝试创建一个JSON请求,以发送到电子邮件服务GetResponse,以便为邮件广告系列添加联系人。

我想要实现的格式是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"
            }
        ]
    }
]

关注How to create JSON string in C#我构建了此设置

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; }
}

这样就填补了这个

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);

此处 json 符合预期

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

我不知道如何正确地将API_KEY字符串添加到其前面。

如何更改此内容,将API_KEY添加到其前面,而不附加属性名称,最好使用JavaScriptSerializer()

2 个答案:

答案 0 :(得分:4)

您需要做的是创建一个类型为object的集合,并将"API_KEY"作为第一个条目传递,将add对象作为第二个条目。

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);

答案 1 :(得分:1)

从文档中看,它们看起来像是以专有方式包装JSON对象。 JSON需要以'{'开头,而不是'''。我会尝试这样的事情:

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