在匿名类型中包含Dictionary,然后序列化以形成json

时间:2014-04-09 02:54:36

标签: c# json dictionary idictionary

在下面的代码中,我有一个字典" nissi_params_fields"我填充了参数:

Dictionary<string, string> nissi_params_fields = new Dictionary<string, string>();
string[] separator = { "," };
string[] dfields = form_fields.Split(separator, StringSplitOptions.RemoveEmptyEntries);
string[] ffields = db_fields.Split(separator, StringSplitOptions.RemoveEmptyEntries);

foreach (var field in ffields)
{
    NissiMain nm = new NissiMain();
    object field_object = nm.nissi_get_object_by_name(field);
    string fieldvalue = nm.nissi_get_object_value_by_name(field_object);
    nissi_params_fields[field] = fieldvalue;
    this.nissiSetStorageItem(save_page, field, fieldvalue);
}
nissi_params_fields["company_id"] = this.nissiGetStorageItem("nissi_base", "ni_companyID");
string nissi_params_id = "";

if (save_type == "edit")
{
    nissi_params_fields["id"] = this.nissiGetStorageItem(save_page, "id");
    nissi_params_id = this.nissiGetStorageItem(save_page, "id");
}

我现在想要创建一个包含上述&#34; nissi_params_fields&#34;的匿名类型。字典作为单个字段&#34;字段&#34;,所以我首先尝试转换&#34; nissi_params_fields&#34;到一个对象&#34; nissi_params_fields_object&#34;我可以在Newtonsoft JObject&#34; nissi_params_object&#34;中使用:

object nissi_params_fields_object = nissi_params_fields.ToArray();

挑战是如何将字典转换为对象......我该怎么做?

我现在想要包含已转换的对象&#34; nissi_params_fields_object&#34;在匿名类型中,然后使用Newtonsoft JObject将整个事物序列化为JSON:

JObject nissi_params_object = JObject.FromObject(new
{
    apikey = this.nissiGetStorageItem("nissi_base", "ni_apiKey"),
    company_id = this.nissiGetStorageItem("nissi_base", "ni_companyID"),
    id = nissi_params_id,
    fields = nissi_params_fields_object,
});

1 个答案:

答案 0 :(得分:0)

如果您只是希望JSON序列化您可以执行的对象:

string jsonString = JsonConvert.SerializeObject(nissi_params_object);

然后将jsonString附加到URL。