如何将C#空列表序列化为JSON空数组?
问题描述:
我将我的代码从使用名为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 []
?
答
您正在处理的dynamic
价值真的是JObject
。它知道如何自动将一些标准类型(如int
s)转换为合适的JValue
对象,但更复杂的任何东西都需要首先明确转换为某种JToken
。
plugin.floatedPlugins = JArray.FromObject(new List<dynamic>());
谢谢,那就是我一直在寻找的。投票将其视为重复关闭。 – TW80000