8

I have a very simple piece of code that I just cannot work out.

JObject obj = new JObject { "Name", "John" };
JArray array = new JArray();

array.Add(obj);
// throws "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject"

I have tried many different things to add a JObject to a JArray. What am I doing wrong?

0

2 Answers 2

17

Your problem is not the adding part.

Your problem is the initialization of your JOject.

Try this.

JObject obj = new JObject();
obj.Add("Name", "John");
Jarray array = new JArray();

array.Add(obj);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! As you typed it I discovered another method too I'll post as a second answer
5

Another way to fix the problem cl0ud pointed out is to instantiate as such:

JObject obj = new JObject { 
  { "Name", pRecord.getName() } 
};
JArray array = new JArray();

array.Add(obj);

Note those extra curly braces

Comments

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.