Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.NET - Add JObject to JArray

Tags:

json

c#

json.net

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?

like image 412
Nick Bull Avatar asked Mar 19 '19 10:03

Nick Bull


1 Answers

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);
like image 79
cl0ud Avatar answered Oct 31 '22 02:10

cl0ud