4

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?

2 Answers 2

3

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"}
Sign up to request clarification or add additional context in comments.

2 Comments

But it is not just properties - also JObjects and JArrays?
Yes, you can add not just primitive tokens like strings but also objects and arrays.
2

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

2 Comments

What if it is empty - how do i check for that? So that i should not add a ,. add the end of the last property
Are you trying to get the members of an object or a list of homogenous objects? You can't simply iterate over properties in a C# object as you could for example in JavaScript. Have you considered using Newtonsoft.Json to serialize and deserialize objects to and from JSON?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.