Dawnkeeper Dawnkeeper - 1 month ago 14
JSON Question

C# Array of anonymous class inside another anonymous class

I deserialize a JSon string that holds an object with an array of subobjects.

The current working solution looks like this:

var definition = new { systems = new subclass[0] };
var ret = JsonConvert.DeserializeAnonymousType(source, definition);

public class subclass
{
public long id;
}


Is there a way to replace the subclass with another anonymous one?

I tried using the following, but only get a compiler error:

var definition = new { constellations = new{ id=0L }[0] };

Answer

I wonder if you could do:

var definition = new { systems = MakeEmptyArrayFrom(new { id = 0L}) };
...
static T[] MakeEmptyArrayFrom<T>(T value) => new T[0];

note: if that works, it will probably also work even if you use something like:

static T[] MakeNullArrayFrom<T>(T value) => null;

as I imagine the library is more interested in the Type than the value.

Comments