2016-08-16 213 views
0

我將我的代碼從使用名爲floatedPlugin的屬性切換爲使用名爲floatedPlugins(注意's')的屬性。此代碼運行後,我完全不需要floatedPlugin。現有的floatedPlugin值將是對象或null。如果它是null,我想將floatedPlugins設置爲空數組。如果floatedPlugin是一個對象,我想將floatedPlugins設置爲僅包含該對象的數組。如何將C#空列表序列化爲JSON空數組?

foreach (var _case in context.Cases) 
{ 
    dynamic data = JsonConvert.DeserializeObject(_case.Data); 

    foreach (var row in data.myRows) 
    { 
     foreach (var plugin in row.plugins) 
     { 
      if (plugin.floatedPlugin == null) 
      { 
       plugin.floatedPlugins = new List<dynamic>(); // Code breaks here 
      } 
      else 
      { 
       plugin.floatedPlugins = new List<dynamic>(plugin.floatedPlugin); 
      } 
     } 
    } 
    _case.Data = JsonConvert.SerializeObject(data); 
} 

試圖運行,這是

Could not determine JSON object type for type System.Collections.Generic.List`1[System.Object]. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentException: Could not determine JSON object type for type System.Collections.Generic.List`1[System.Object]. 

,當我得到的錯誤什麼我需要做的就是floatedPlugins序列化到所產生的序列化JSON []

+1

謝謝,那就是我一直在尋找的。投票將其視爲重複關閉。 – TW80000

回答

2

您正在處理的dynamic價值真的是JObject。它知道如何自動將一些標準類型(如int s)轉換爲合適的JValue對象,但更復雜的任何東西都需要首先明確轉換爲某種JToken

plugin.floatedPlugins = JArray.FromObject(new List<dynamic>());