TW80000 TW80000 - 3 months ago 42
JSON Question

How to serialize a C# empty list into a JSON empty array?

I am switching my code from using a property called

floatedPlugin
to using a property called
floatedPlugins
(note the 's'). I don't need
floatedPlugin
to exist at all after this code runs. An existing
floatedPlugin
value will either be an object or
null
. If it's
null
, I want to set
floatedPlugins
to be an empty array. If
floatedPlugin
is an object, I want to set
floatedPlugins
to an array containing solely that object.

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);
}


The error I get when trying to run this is

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].


What do I need to do to get
floatedPlugins
to serialize into
[]
in the resulting serialized JSON?

Answer

The dynamic value that you are dealing with is really JObject under the hood. It knows how to automatically convert some standard types (like ints) to the appropriate JValue objects, but anything more complicated needs to be explicitly turned into some kind of JToken first.

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