What's the syntax to create an object that is an array of objects with JObject?
Try JToken
or JArray
.
var Config = JToken.FromObject( new List<Question> { new Question { Key = "contact", Label = "Contact Person", HelpText = "", Config = JObject.FromObject(new {}), Type = "text", ContextTarget = "$.data.contact" }, new Question { Key = "company", Label = "Company Name", HelpText = "", Config = JObject.FromObject(new {}), Type = "text", ContextTarget = "$.data.company" } } );var result = Config.ToString();
The result is:
[{ "Label": "Contact Person", "HelpText": "", "Type": "text", "ContextTarget": "$.data.contact", "Config": {}, "Key": "contact"},{ "Label": "Company Name", "HelpText": "", "Type": "text", "ContextTarget": "$.data.company", "Config": {}, "Key": "company"}]
You need to know what type of JToken
you want to create. For example, you can create a JObject
either from a string value or from a .NET object
. They are like factory methods. For example, if you want to create it from List<string>
, you will have to tell the framework you will be creating a JArray
from an in memory object
:
var fromArray = JArray.FromObject(new List<string> { "One", "Two" });
Or that you will be creating JObject
:
var fromObj = JObject.FromObject(new Customer() { Name = "Jon" });
Or you can create the tokens from JSON:
var fromJson = JArray.Parse("[\"One\", \"Two\"]");
Finally, you can just create JToken
which is the parent of all the above classes (JArray
, JObject
) but then you will only have access to JToken
properties and methods:
var Config = JToken.FromObject( new List<string> { "One", "Two" });
See this for the various tokens.
so the C# code I needed to do so was:
Config = JObject.FromObject(new { questions = JArray.FromObject( new List<Question> { new Question { Key = "contact", Label = "Contact Person", HelpText = "", Config = emptyJObject, Type = "text", ContextTarget = "$.data.contact" }, new Question { Key = "company", Label = "Company Name", HelpText = "", Config = emptyJObject, Type = "text", ContextTarget = "$.data.company" } }) })