4

I tried

JObject obj = new JObject();
obj["item1"] =  new string[] {"a","b"};

and got

Cannot implicitly convert type 'string[]' to 'Newtonsoft.Json.Linq.JToken'

How do I add a string array to a JObject? Also, why do I get that error?

1 Answer 1

8

Try this way:

JObject obj = new JObject();
obj.Add("item1", JToken.FromObject(new[] { "a", "b" }));
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks it works. I tried obj.Add("item1", JArray.FromObject(new[] { "a", "b" })); too and it worked. What is the difference?
@Johnwebner Basically, a JToken can be an object or an array, a JArray can only be an array
Looks like obj.Add("item1", JToken.FromObject(new[] { "a", "b" })); converts the JToken into a JArray. obj["item1"].GetType(); results in {Name = "JArray" FullName = "Newtonsoft.Json.Linq.JArray"}

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.