Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JObject - adding new objects dynamically

I have a JObject like this:

JObject grid =
            new JObject(
            new JProperty("myprop", "value 1"),
            new JProperty("name", 
                new JArray(
                                new JObject(
                        new JProperty("myprop2", "value 2")
                    )
                )
            )
        )

Nothing wrong with that.

But, I have an object that I want to iterate over, and add them to my JObject, but how to do that?

Like this? (which is not valid, I know)

JObject grid =
            new JObject(
            new JProperty("myprop", "value 1"),
            new JProperty("name", 
                new JArray(
                                new JObject(
                        new JProperty("myprop2", "value 2"),
                        foreach(var value in myObject) {
                            new JObject(
                                new JProperty(value.Name, value.Value)
                            )   
                        }
                    )
                )
            )
        )

How can I do this?

like image 899
brother Avatar asked Sep 08 '25 02:09

brother


2 Answers

You can also add properties to an existing JObject:

var obj = new JObject();
Console.WriteLine(obj.ToString()); // {}

obj.Add("key", "value");
Console.WriteLine(obj.ToString()); // {"key": "value"}
like image 126
Oliver Hanappi Avatar answered Sep 10 '25 12:09

Oliver Hanappi


If you know your array items in advance why not create them first?

var myprop2Items = new List<JObject>();

foreach(var value in myObject) {
                            myprop2Items.Add(new JObject(
                                new JProperty(value.Name, value.Value)
                            ));

} 


JObject grid =
            new JObject(
            new JProperty("myprop", "value 1"),
            new JProperty("name", 
                new JArray(
                                new JObject(
                        new JProperty("myprop2", "value 2"),
                        myprop2Items
                        )
                    )
                )
            )
        )
like image 44
bash.d Avatar answered Sep 10 '25 10:09

bash.d