Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dynamic ExpandoObject Array

Tags:

c#

please tell me, how do I get the json like this:

    dynamic packet = new ExpandoObject();
    packet.type = "somethink";
    packet.user = 12345;

    packet.nets[0].amout = 123;
    packet.nets[0].lower = 0;
    packet.nets[1].amout = 345;
    packet.nets[1].lower = 1;
    string input = Newtonsoft.Json.JsonConvert.SerializeObject(packet);

Its not workig, error: An unhandled exception of type "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" in System.Core.dll

For more information: "System.Dynamic.ExpandoObject" does not contain definitions of "nets"

Thanks.

like image 541
Иван Иванов Avatar asked Dec 05 '22 18:12

Иван Иванов


2 Answers

It's the ExpandoObject who's a dynamic object. The rest of properties should be other ExpandoObject instances or regular objects, arrays, collections...

For example:

packet.nets = new[] 
{
     new { amount = 123, lower = 0 },
     new { amount = 345, lower = 1 }
}

Or:

packet.nets = new[]
{
     new Dictionary<string, int> { { "amount", 345 }, { "lower", 0 } },
     new Dictionary<string, int> { { "amount", 123 }, { "lower", 1 } }
}

There're many other approaches, including the use of instances of concrete classes.

like image 92
Matías Fidemraizer Avatar answered Dec 15 '22 00:12

Matías Fidemraizer


Firstly, you need create nets in packet object, like this:

packet.nets = new dynamic[2];

And initialize the objects in nets, if you want with `ExpandoObject too:

packet.nets[0] = new ExpandoObject();
packet.nets[1] = new ExpandoObject();

Then is done, complete code:

dynamic packet = new ExpandoObject();
packet.type = "somethink";
packet.user = 12345;

packet.nets = new dynamic[2];

packet.nets[0] = new ExpandoObject();
packet.nets[0].amout = 123;
packet.nets[0].lower = 0;

packet.nets[1] = new ExpandoObject();
packet.nets[1].amout = 345;
packet.nets[1].lower = 1;            

string input = Newtonsoft.Json.JsonConvert.SerializeObject(packet);
like image 31
Arturo Menchaca Avatar answered Dec 15 '22 00:12

Arturo Menchaca