简体   繁体   中英

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?

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

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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM