将JSON对象存储在JSON对象的属性中

时间:2019-01-11 08:01:09

标签: c# json

我如何在JSON对象的属性中存储JSON对象,我的意思是JSON对象的属性值是另一个JSON对象。我有一个DataTable dt,我从DataBase读取数据并将其存储在此DataTable中。

using (var da = new SqlDataAdapter(command))
{
         command.CommandType = CommandType.StoredProcedure;
         da.Fill(dt);
}

现在,我在此数据表中添加一列

dt.Columns.Add("attributes");

现在,我创建一个JObject并将其值存储在DataTable的每一行的“属性”列中

dynamic attributeValue = new JObject();
attributeValue.type = "Stage_FF_Hot_Alerts__c";

foreach (DataRow d in dt.Rows)
{
       d["attributes"] = attributeValue;
}

现在,我将此数据表序列化

string JSONresult = JsonConvert.SerializeObject(dt);

我得到的结果是

{
  "attributes" : "{"type" : "Stage_FF_Hot_Alerts__c"}",
  "Address__c"   : "Street",
  "AgentID__c"   : "123456",
  "Alert_Status__c"  : "Closed",
  "BusinessUnit__c"  : "INFINITI",
  "Case_Type__c" : "INFINITI Service",
  "City__c"      : "City",
  "ContactId__c"     : "10951",
  "DayTimePhone__c"     : "123456789",
  "DealerCode__c"    : "72067",
  "DealerName__c"    : "Infiniti Of Kansas City",
  "EmailAddress__c"  : "INF@isky.com",
  "EveningPhone__c"  : "123456789",
  "FirstName__c" : "CustomerFirstName",
  "HotAlertType__c"  : "Hot Alert",
  "LastName__c"  : "CustomerSurname",
  "NPS_Score_1__c"   : "0",
  "V01_Alert_Trigger__c"     : "Which of the following best describes your overall service experience?",
  "Field_Open_Date__c"   : "2018-08-05"
}

我想要的结果是

{
  "attributes" : {"type" : "Stage_FF_Hot_Alerts__c"},
  "Address__c"   : "Street",
  "AgentID__c"   : "123456",
  "Alert_Status__c"  : "Closed",
  "BusinessUnit__c"  : "INFINITI",
  "Case_Type__c" : "INFINITI Service",
  "City__c"      : "City",
  "ContactId__c"     : "10951",
  "DayTimePhone__c"     : "123456789",
  "DealerCode__c"    : "72067",
  "DealerName__c"    : "Infiniti Of Kansas City",
  "EmailAddress__c"  : "INF@isky.com",
  "EveningPhone__c"  : "123456789",
  "FirstName__c" : "CustomerFirstName",
  "HotAlertType__c"  : "Hot Alert",
  "LastName__c"  : "CustomerSurname",
  "NPS_Score_1__c"   : "0",
  "V01_Alert_Trigger__c"     : "Which of the following best describes your overall service experience?",
  "Field_Open_Date__c"   : "2018-08-05"
}

1 个答案:

答案 0 :(得分:1)

示例代码中的以下行正在DataTable中创建一列,但未指定数据类型,因此类型为defaults to string

dt.Columns.Add("attributes");

尝试使用可指定所需类型的重载,例如:

dt.Columns.Add("attributes", typeof(object));

或者也许:

dt.Columns.Add("attributes", typeof(JObject));