2014-04-14 20 views
1

我试图创建以下格式写作列表为JObject

{history_dates: 
    [ 
     {start_date: "2014-03-02" status: "Added" end_date: "2014-03-02"}, 
     {start_date: "2014-04-02" status: "Added" end_date: "2014-04-02"}, 
     {start_date: "2014-05-02" status: "Deleted" end_date: "2014-05-02"} 
    ]} 

它试图d添加到JChild时刻的JObject,崩溃!

 JObject jChild = new JObject(); 
     for (int i = 0; i < m_iHistCount; i++) 
     { 
      string endDate = ""; 
      if (m_dtEndDate[i] != GetDefaultDate()) 
      { 
       endDate = m_dtEndDate[i].ToString("yyyy-MM-dd"); 
      } 
      var d = new { start_date = m_dtHistory[i].Date.ToString("yyyy-MM-dd"), status = (SYNC_STATUS)histDtSyncStatus[i], end_date = endDate }; 
      jChild.Add(d); 
     } 

这是不是正确的方法?

+0

这似乎不是有效的Json。你能证实这是你得到的回应吗? – ua741

回答

1

看来你尝试了错误的方式。请检查下面的例子:

//declare JArray to store history_dates value 
JArray historyDates = new JArray(); 
for (int i = 0; i < m_iHistCount; i++) 
{ 
    string endDate = ""; 
    if (m_dtEndDate[i] != GetDefaultDate()) 
    { 
     endDate = m_dtEndDate[i].ToString("yyyy-MM-dd"); 
    } 
    var d = string.Format("{{ \"start_date\" = \"{0}\", \"status\" = \"{1}\", \"end_date\" = \"{2}\"}}", 
            m_dtHistory[i].Date.ToString("yyyy-MM-dd"), 
            (SYNC_STATUS)histDtSyncStatus[i], 
            endDate); 
    historyDates.Add(d); 
} 

JObject root = new JObject(); 
//add property history_dates and assign above mentioned JArray as the property value 
root.Add("history_dates", historyDates); 

你也可以构建匿名对象,然后将其序列化到字符串如下:

var d = new { start_date = m_dtHistory[i].Date.ToString("yyyy-MM-dd"), status = (SYNC_STATUS)histDtSyncStatus[i], end_date = endDate }; 
historyDates.Add(JsonConvert.SerializeObject(d)); 

但是这将是更有效的构建JSON字符串在首位