Frekster
Frekster

Reputation: 1148

C# How do I add a json array of items to an ExpandoObject?

How do I create prop3 and include the opening ([) and closing (]) braces in the ExpandoObject syntax?

prop3 is an array so how do I add userId and userName to the ExpandoObject?

{
    "prop1": "value1",
    "prop2": "value2",
    "prop3": [
        "userId",
        "userName"
    ],
}
    
// my ExpandoObject syntax
    
dynamic form = new ExpandoObject();
    
form.prop1 = "value1";
form.prop2 = "value2";
    
// what ExpandoObject syntax do I use to add the the json array now 
// including the [ ] and each single value to the array?

Upvotes: 0

Views: 391

Answers (2)

Mocas
Mocas

Reputation: 1660

You can use this

form.prop3 = new[] { "userId", "userName" };

Upvotes: 1

Jamshaid K.
Jamshaid K.

Reputation: 4567

First, you will need to initialize the property with dynamic array then you can use the indexes to put values there. See:

dynamic form = new ExpandoObject();
form.prop1 = "value1";
form.prop2 = "value2";
form.prop3 = new dynamic[2]; // initialized with 2 indexes
form.prop3[0] = "userId"; 
form.prop3[1] = "userName";

And this is the response that you get if you generate the Json:

{
  "prop1": "value1",
  "prop2": "value2",
  "prop3": [
    "userId",
    "userName"
  ]
}

Upvotes: 0

Related Questions