Add new json object to existing json object in C# - c#

I want to add a new playlist with songs to an existing json file.
I'm using Newtonsoft Json.NET to create a Json file like this:
dynamic GroupObj = new JObject();
GroupObj.Playlist = new JArray() as dynamic;
dynamic PlayListObj = new JObject();
PlayListObj.UniqueId = "";
PlayListObj.Title = "Playlist name";
GroupObj.Playlist.Add(PlayListObj);
PlayListObj.Songs = new JArray() as dynamic;
dynamic SongObj = new JObject();
SongObj.UniqueId = "";
SongObj.Title = "song name";
PlayListObj.Songs.Add(SongObj);
data = GroupObj.ToString();
That outputs this:
{
"Playlist": [
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
}
]
}
]
}
How would I modify the Json.NET to add new Objects to the existing Object to get to something like this:
{
"Playlist": [
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
}
]
},
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
"Lyrics": "song lyrics",
"Location": "location"
}
]
}
]
}

Nevermind, I made a solution by rewriting the whole file. Probably not very resource friendly but for a school project, it works. Thanks
string data;
JsonValue val = JsonValue.Parse("{\"some json data\": some value,}");
JsonArray Pl = val.GetObject().GetNamedArray("Playlist");
for (uint x = 0; x != Pl.Count; x++)//go through each playlist
{
var Pl_title = Pl.GetObjectAt(x).GetNamedString("Title"); //get playlist name
if (Pl_title != txtPlaylistName.Text)//dont do anything if playlist exists
{
var Pl_id = Pl.GetObjectAt(x).GetNamedString("UniqueId");
var Pl_loc = Pl.GetObjectAt(x).GetNamedString("Location");
var Pl_img = Pl.GetObjectAt(x).GetNamedString("ImagePath");
//re-create the playlist
dynamic PlayListObj = new JObject();
PlayListObj.UniqueId = Pl_id;
PlayListObj.Title = Pl_title;
PlayListObj.Location = Pl_loc;
PlayListObj.ImagePath = Pl_img;
GroupObj.Playlist.Add(PlayListObj);
PlayListObj.Songs = new JArray() as dynamic;
JsonArray Sng = Pl.GetObjectAt(x).GetNamedArray("Songs");
for (uint y = 0; y != Sng.Count; y++)
{
var Sng_id = Sng.GetObjectAt(y).GetNamedString("UniqueId");
var Sng_title = Sng.GetObjectAt(y).GetNamedString("Title");
var Sng_lyr = Sng.GetObjectAt(y).GetNamedString("Lyrics");
var Sng_loc = Sng.GetObjectAt(y).GetNamedString("Location");
//re-create the songs in the playlist
dynamic SongObj = new JObject();
SongObj.UniqueId = Sng_id;
SongObj.Title = Sng_title;
SongObj.Lyrics = Sng_lyr;
SongObj.Location = Sng_loc;
PlayListObj.Songs.Add(SongObj);
}
}
else
txtBerror.Text = "The name: " + txtPlaylistName.Text + " already exists.";
}
if (txtPlaylistName.Text != string.Empty)
{
//re-create the playlist
dynamic newPlayListObj = new JObject();
newPlayListObj.UniqueId = "PL " + txtPlaylistName.Text;
newPlayListObj.Title = txtPlaylistName.Text;
newPlayListObj.Location = "";
newPlayListObj.ImagePath = "";
GroupObj.Playlist.Add(newPlayListObj);
newPlayListObj.Songs = new JArray() as dynamic;
for (int a = 0; a != 3; a++)//number of songs
{
dynamic SongObj = new JObject();
SongObj.UniqueId = "Sng " + "file name";
SongObj.Title = "file name";
SongObj.Lyrics = "";
SongObj.Location = "";
newPlayListObj.Songs.Add(SongObj);
}
}
else
txtBerror.Text = "Enter a playlist name";
data = GroupObj.ToString();
await Windows.Storage.FileIO.WriteTextAsync(newFile, data);//write to the file

Related

How to serialize sql data without the column names?

I am Serializing data from SQL database to JSON, how can I serialize just the values without the string name OR a function to trim the serialized JSON before Deserializing.
I read about ScriptIgnoreAttribute but didn't see how to relate it with what I want to do
Original JSON
​[
{
"CODE": "AF",
"TOTALVALUE": "$23,554,857.27"
},
{
"CODE": "AS",
"TOTALVALUE": "$38,379,964.65"
},
{
"CODE": "SG",
"TOTALVALUE": "$24,134,283.47"
}
]
Desired JSON
​[
{
"AF": "$23,554,857.27"
},
{
"AS": "$38,379,964.65"
},
{
"SG": "$24,134,283.47"
}
]
SQL View structure
My SQL query to return the data
SELECT [CODE],[TOTALVALUE] FROM [dbo].[vw_BuyersByCountryValue]
enter code here
Code for Serializing in ASP.NET
[WebMethod]
public void GetBuyersByCountryValue()
{
using (PMMCEntities ctx = new PMMCEntities())
{
ctx.Configuration.ProxyCreationEnabled = false;
var qry = ctx.vw_BuyersByCountryValue.ToList();
var js = new JavaScriptSerializer();
string strResponse = js.Serialize(qry);
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.AddHeader("content-length", strResponse.Length.ToString(CultureInfo.InvariantCulture));
Context.Response.Flush();
Context.Response.Write(strResponse);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
It is very simple
// data from the query
// SELECT CODE, TOTALVALUE FROM vw_BuyersByCountryValue
var sqldata = new []
{
new { Code = "AF", TotalValue = "$23,554,857.27" },
new { Code = "AS", TotalValue = "$38,379,964.65" },
new { Code = "SG", TotalValue = "$24,134,283.47" },
};
var mappeddata = sqldata.Select( r =>
{
var dict = new Dictionary<string,string>();
dict[r.Code] = r.TotalValue;
return dict;
});
var json = JsonConvert.SerializeObject(mappeddata,Formatting.Indented);
content of json
[
{
"AF": "$23,554,857.27"
},
{
"AS": "$38,379,964.65"
},
{
"SG": "$24,134,283.47"
}
]
.net fiddle sample
You can even populate it as
{
"AF": "$23,554,857.27",
"AS": "$38,379,964.65",
"SG": "$24,134,283.47"
}
with
var sqldata = new []
{
new { Code = "AF", TotalValue = "$23,554,857.27" },
new { Code = "AS", TotalValue = "$38,379,964.65" },
new { Code = "SG", TotalValue = "$24,134,283.47" },
};
var mappeddata = sqldata.ToDictionary(r => r.Code, r => r.TotalValue);
var json = JsonConvert.SerializeObject(mappeddata,Formatting.Indented);
.net fiddle sample
Update
[WebMethod]
public void GetBuyersByCountryValue()
{
using (PMMCEntities ctx = new PMMCEntities())
{
ctx.Configuration.ProxyCreationEnabled = false;
var qry = ctx.vw_BuyersByCountryValue.ToList();
var mapped = qry.Select r =>
{
var dict = new Dictionary<string,string>();
dict[r.CODE] = r.TOTALVALUE;
return dict;
});
string strResponse = Newtonsoft.Json.JsonConvert.SerializeObject(mapped);
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.AddHeader("content-length", strResponse.Length.ToString(CultureInfo.InvariantCulture));
Context.Response.Flush();
Context.Response.Write(strResponse);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
You need the NuGet package Newtonsoft.Json

C# bot framework Align checkboxes in adaptive card along a row

We have an adaptive card which is displayed after getting an answer from QnA. Within the card, we have choiceset displayed to let the user select the category he is interested in. Upon clicking select, the second level of options are given. However, we are planning to have the suboptions in the same card at first level. Is it possible to have checkboxes side by side in an adaptive card?
Code:
public List<Attachment> EmbedAdaptiveCategoryOptions()
{
#region populate choiceLists
List<AdaptiveChoice> OGChoice = new List<AdaptiveChoice>();
List<AdaptiveChoice> GeoChoice = new List<AdaptiveChoice>();
List<AdaptiveChoice> TechChoice = new List<AdaptiveChoice>();
List<AdaptiveChoice> ThemeChoice = new List<AdaptiveChoice>();
List<AdaptiveChoice> OKChoice = new List<AdaptiveChoice>();
List<string> OGids = new List<string>();
List<string> Geoids = new List<string>();
List<string> Techids = new List<string>();
List<string> themeids = new List<string>();
List<string> feedbackids = new List<string> { "I am good with the link already shared with me above!" };
List<CardAction> OGButtons = CreateOGButtons(out OGids);
foreach (var item in OGButtons)
{
OGChoice.Add(new AdaptiveChoice() { Title = item.Title, Value = item.Value.ToString() });
}
List<CardAction> GeoButtons = CreateGeoButtons(out Geoids);
foreach (var item in GeoButtons)
{
GeoChoice.Add(new AdaptiveChoice() { Title = item.Title, Value = item.Value.ToString() });
}
List<CardAction> techcardButtons = CreateTechButtons(out Techids);
foreach (var item in techcardButtons)
{
TechChoice.Add(new AdaptiveChoice() { Title = item.Title, Value = item.Value.ToString() });
}
List<CardAction> themecardButtons = CreateThemeButtons(out themeids);
foreach (var item in themecardButtons)
{
ThemeChoice.Add(new AdaptiveChoice() { Title = item.Title, Value = item.Value.ToString() });
}
List<CardAction> feedbackcardButtons = new List<CardAction>();
CardAction feedbackButton = new CardAction()
{
Value = "feedback",
Type = "imBack",
Title = "I am good with the link already shared with me above!"
};
feedbackcardButtons.Add(feedbackButton);
foreach (var item in feedbackcardButtons)
{
OKChoice.Add(new AdaptiveChoice() { Title = item.Title, Value = item.Value.ToString() });
}
#endregion
AdaptiveCard card = new AdaptiveCard();
List<Attachment> attachments = new List<Attachment>();
AdaptiveColumnSet Title = new AdaptiveColumnSet();
AdaptiveColumn titletext = new AdaptiveColumn();
titletext.Width = AdaptiveColumnWidth.Auto;
titletext.Items.Add(new AdaptiveTextBlock()
{
Weight = AdaptiveTextWeight.Bolder,
Wrap = true,
Text = "Are you interested in searching through the file? Please select the Category you would like to refine Credentials for:",
Size = AdaptiveTextSize.Medium
});
Title.Columns.Add(titletext);
card.Body.Add(Title);
AdaptiveColumnSet abc = new AdaptiveColumnSet();
AdaptiveColumn col1 = new AdaptiveColumn();
col1.Width = AdaptiveColumnWidth.Auto;
col1.Type = "TextBlock";
col1.Items.Add(new AdaptiveChoiceSetInput()
{
Choices = OGChoice,
Separator = true,
IsMultiSelect = true,
Type = "Input.ChoiceSet"
});
AdaptiveColumn col2 = new AdaptiveColumn();
col2.Width = AdaptiveColumnWidth.Auto;
col2.Type = "TextBlock";
//col2.Type = AdaptiveTextBlock.TYPE;
col2.Items.Add(new AdaptiveChoiceSetInput()
{
Choices = GeoChoice,
Separator = true,
IsMultiSelect = true,
Type = "Input.ChoiceSet"
});
AdaptiveColumn col3 = new AdaptiveColumn();
col3.Width = AdaptiveColumnWidth.Auto;
col3.Type = "TextBlock";
//col2.Type = AdaptiveTextBlock.TYPE;
col3.Items.Add(new AdaptiveChoiceSetInput()
{
Choices = TechChoice,
Separator = true,
IsMultiSelect = true,
Type = "Input.ChoiceSet"
});
AdaptiveColumn col4 = new AdaptiveColumn();
col4.Width = AdaptiveColumnWidth.Auto;
col4.Type = "TextBlock";
//col2.Type = AdaptiveTextBlock.TYPE;
col4.Items.Add(new AdaptiveChoiceSetInput()
{
Choices = ThemeChoice,
Separator = true,
IsMultiSelect = true,
Type = "Input.ChoiceSet"
});
AdaptiveColumn col5 = new AdaptiveColumn();
col5.Width = AdaptiveColumnWidth.Auto;
col5.Type = "TextBlock";
//col2.Type = AdaptiveTextBlock.TYPE;
col5.Items.Add(new AdaptiveChoiceSetInput()
{
Choices = OKChoice,
Separator = true,
IsMultiSelect = true,
Type = "Input.ChoiceSet"
});
abc.Columns.Add(col1);
abc.Columns.Add(col2);
abc.Columns.Add(col3);
abc.Columns.Add(col4);
abc.Columns.Add(col5);
card.Body.Add(abc);
List<AdaptiveAction> Actions = new List<AdaptiveAction>()
{
new AdaptiveSubmitAction()
{
Id = "selectBtn",
Title = "Select",
Speak = "<s>Search</s>",
DataJson = "{ \"Type\": \"SubmitQuestion\" }"
}
};
card.Actions.Add(Actions[0]);
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = card
};
attachments.Add(attachment);
return attachments;
}
You can align check boxes side-by-side in an AdaptiveCard by placing them in columns. Take a look at the AdaptiveCards documentation on columns and see the example below.
Screenshot
AdaptiveCard JSON
{
"type": "AdaptiveCard",
"body": [
{
"type": "TextBlock",
"horizontalAlignment": "Center",
"size": "Medium",
"text": "Horizontal Checkboxes",
"maxLines": 3
},
{
"type": "ColumnSet",
"separator": true,
"columns": [
{
"type": "Column",
"items": [
{
"type": "Input.Toggle",
"id": "option1",
"title": "Option 1",
"value": "true"
}
],
"width": "auto"
},
{
"type": "Column",
"items": [
{
"type": "Input.Toggle",
"id": "option2",
"title": "Option 2",
"value": "false"
}
],
"width": "auto"
},
{
"type": "Column",
"items": [
{
"type": "Input.Toggle",
"id": "option3",
"title": "Option 3",
"value": "true"
}
],
"width": "auto"
},
{
"type": "Column",
"items": [
{
"type": "Input.Toggle",
"id": "option4",
"title": "Option 4",
"value": "false"
}
],
"width": "auto"
}
]
}
],
"actions": [
{
"type": "Action.Submit",
"title": "Submit"
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0"
}
Also, I would recommend using the AdaptiveCard Designer to help format and create your cards.
Hope this helps!

Pastel Partner SDK Create Invoice Issue

I am trying to generate an invoice in Pastel Partner using the SDK from a C# application. I have followed the documentation to a tee but I keep on getting a return code of 17 (Invalid customer account code). I have verified that the customer exists.
public string GenerateInvoiceDocument(Order order)
{
var result = _sdk.SetDataPath($"{_directory}{_company}");
if (result == "0") _sdk.OpenDocumentFiles();
var customer = GetCustomer(order.CustomerNumber);
if (result == "0") {
var header = "|||OIL004|05/03/2017||N|0|Message no.1|Message no.2|Message no.3|Delivery no.1|Delivery no.2|Delivery no.3|Delivery no.4|Delivery no.5||00||05/03/1999|011-7402156|Johnny|011-7402157|1";
result =_sdk.DefineDocumentHeader(header);
}
for (var x = 0; x < order.InventoryCode.Count; x++)
{
if (result == "0")
{
var customerPrice = GetCustomerPrice(customer.Number, order.InventoryCode[x]);
result = _sdk.DefineDocumentLine(
GenerateDocumentLine(
0,
Convert.ToDouble(order.Quantity[x]),
customerPrice.Price[x],
customerPrice.IncPrice[x],
"",
customer.TaxCode.ToString().PastelZeroPad(2),
"",
"",
customerPrice.ItemCode,
order.InventoryCode[x],
"4",
"002",
""));
}
}
result = _sdk.ImportDocument(3);
_sdk.CloseDocumentFiles();
return result;
}
Seems like a bit of buggy behaviour from Pastel, the solution was to remove any calcs from the Pastel flow by doing them beforehand.
public string GenerateInvoiceDocument(Order order)
{
var customer = GetCustomer(order.CustomerNumber);
var header = GenerateCustomerDocumentHeader(customer, DateTime.Now.AddYears(-1), order.Number, "", "", "", "", "", "", "", "", "", "", DateTime.Now.AddYears(-1), "", "", "", 1);
var lines = new List<string>();
for (var x = 0; x < order.InventoryCode.Count; x++)
{
var customerPrice = GetCustomerPrice(order.CustomerNumber, order.InventoryCode[x]);
var newLine = GenerateDocumentLine(customerPrice.Price[x], (double)order.Quantity[x], customerPrice.Price[x], customerPrice.IncPrice[x], "0", customer.TaxCode.ToString(), "", "0", order.InventoryCode[x], order.InventoryDescription[x], "4", "001", "");
lines.Add(newLine);
}
var result = _sdk.SetDataPath($"{_directory}{_company}");
_sdk.OpenDocumentFiles();
result = _sdk.DefineDocumentHeader(header, true);
foreach (var line in lines)
{
result = _sdk.DefineDocumentLine(line);
}
result = _sdk.ImportDocument(3, 0);
_sdk.CloseDocumentFiles();
return result;
}

How to add \r\n\ in json Using c#

I do have a hard code json,I have to send that in http request using post,
This is the json
{
"RequestHeader": {
"UserName": " ",
"Password": " "
},
"RequestBody": {
"ChannelType": 1,
"BillAccountNumber": "1075-001",
"BillAccountType": null,
"PaymentAmount": 15.05,
"FeeAmount": 3.50,
"ABA": "111993776",
"BankAccount": "1234567899",
"EmailAddress": "jonah#doe.org",
"AccountHolder": "JonahDoe",
"WaiveFee": false,
"Recurring": false,
"CustomData": null
}
}
When i am passing this i am getting the right response
But when i am using the other it is not giving the response what i need, The only difference in first one my hard coded have \r\n and the 2nd one below don't have.
{
"RequestHeader": {
"UserName": " ",
"Password": " "
},
"RequestBody": {
"ChannelType": 1,
"BillAccountNumber": "1075-001",
"BillAccountType": null,
"PaymentAmount": 15.05,
"FeeAmount": 3.5,
"ABA": "111993776",
"BankAccount": "1234567899",
"EmailAddress": "jonah#doe.org",
"AccountHolder": "Jonah Doe",
"WaiveFee": false,
"Recurring": false,
"CustomData": null
}
}
Can some body tell me what is the problem.
Code IS:
class Program
{
static void Main(string[] args)
{
var RequestBody = new RequestBody
{
ChannelType = 1,
BillAccountNumber = "1075-001",
BillAccountType = null,
PaymentAmount = 15.05,
FeeAmount = 3.50,
ABA = "111993776",
BankAccount = "1234567899",
EmailAddress = "jonah#doe.org",
AccountHolder = "Jonah Doe",
WaiveFee = false,
Recurring = false,
CustomData = null
};
var RequestHeader = new RequestHeader
{
UserName = "myUname",
Password = "MyPass"
};
var Request = new Request
{
RequestBody = RequestBody,
RequestHeader = RequestHeader,
};
var ApiCredentials = new ApiCredentials
{
Request = Request
};
var httpWReq = (HttpWebRequest)WebRequest.Create("https://gw1.cwplab.com/api/Gateway/AuthorizeCheck");
httpWReq.ContentType = "application/json";
//httpWReq.Credentials = new NetworkCredential(" ", " ");
string data = "{\r\n\"RequestHeader\":{\r\n\"UserName\":\" \",\r\n\"Password\":\" \"\r\n},\r\n\"RequestBody\":{\r\n \"ChannelType\":1,\r\n \"BillAccountNumber\":\"1075-001\",\r\n \"BillAccountType\":null,\r\n \"PaymentAmount\":15.05,\r\n \"FeeAmount\":3.50,\r\n \"ABA\":\"111993776\",\r\n \"BankAccount\":\"1234567899\",\r\n \"EmailAddress\":\"jonah#doe.org\",\r\n \"AccountHolder\":\"Jonah Doe\",\r\n \"WaiveFee\":false,\r\n \"Recurring\":false,\r\n \"CustomData\":null\r\n}\r\n}\r\n";//Request.ToJSON();
string data1 = Newtonsoft.Json.JsonConvert.SerializeObject(Request);
httpWReq.ContentLength = data.Length;
httpWReq.Method = "POST";
using (StreamWriter stream = new StreamWriter(httpWReq.GetRequestStream()))
{
stream.Write(data);
//stream.Flush();
//stream.Close();
};
dynamic httpResponse = (HttpWebResponse)httpWReq.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadKey();
}
}
}
There is a difference in the JSON. I suspect your server doesn't accept the second json (you say you get the wrong response). \r\n are not mandatory, it is just for the reader.
"FeeAmount": 3.5,
"FeeAmount": 3.50,
And
"AccountHolder": "Jonah Doe",
"AccountHolder": "JonahDoe",

Create nested json with c#

I am able to create a flat serialized JSON string pretty easily with c#
My issue is I want to create a nested string like this below
[ {
title: "Yes",
id : "1",
menu: [ {
title: "Maybe",
id : "3",
alert : "No",
menu: [ {
title: "Maybe Not",
id : "8",
alert : "No",
menu: []
} ]
} ]
},
{
title: "No",
id : "2",
menu: []
}]
Any help would be great
Are you using MVC 3? - Do something like:
return Json(myObectWithListProperties, JsonRequestBehavior.AllowGet);
I use this to return complex C# objects that match the structure of the JavaScript objects I want.
e.g.:
var bob = new {
name = "test",
orders = new [] {
new { itemNo = 1, description = "desc" },
new { itemNo = 2, description = "desc2" }
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
gives:
{
"name": "test",
"orders": [
{
"itemNo": 1,
"description": "desc"
},
{
"itemNo": 2,
"description": "desc2"
}
]
}
EDIT: A bit more nesting for fun:
var bob = new {
name = "test",
orders = new [] {
new { itemNo = 1, description = "desc" },
new { itemNo = 2, description = "desc2" }
},
test = new {
a = new {
b = new {
something = "testing",
someOtherThing = new {
aProperty = "1",
another = "2",
theThird = new {
bob = "quiteDeepNesting"
}
}
}
}
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
gives:
{
"name": "test",
"orders": [
{
"itemNo": 1,
"description": "desc"
},
{
"itemNo": 2,
"description": "desc2"
}
],
"test": {
"a": {
"b": {
"something": "testing",
"someOtherThing": {
"aProperty": "1",
"another": "2",
"theThird": {
"bob": "quiteDeepNesting"
}
}
}
}
}
}
Try using
using System.Web.Script.Serialization;
//Assumed code to connect to a DB and get data out using a Reader goes here
Object data = new {
a = reader.GetString(field1),
b = reader.GetString(field2),
c = reader.GetString(field3)
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(data);
This is built-in and saves you the work of serializing to JSON yourself!
This example assumes you are getting data from a database using some sort of reader, and it then constructs the object you want to serialize using an anonymous class. Your anonymous class can be as simple or complex as you need it to be and the JavaScriptSerializer will handle transforming it to JSON. This approach is also useful because you can easily control the JSON property names it will create in the JSON.
using System.Web.Script.Serialization;
var strNJson = new
{
to = "hello",
notification = new
{
title = "textTitle",
body = "bodyText"
}
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(strNJson);
{ "to":"hello",
"notification": {
"title":"titleText",
"body":"bodyText"
}
}
You can make use of the ExpandoObject under the System.Dynamic namespace.
Here is a small snippet for achieving your solution:
dynamic parameters = new dynamic[2];
parameters[0] = new ExpandoObject();
parameters[0].title = "Yes";
parameters[0].id = "1";
parameters[0].menu = new dynamic[1];
parameters[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].title = "Maybe";
parameters[0].menu[0].id = "3";
parameters[0].menu[0].alert = "No";
parameters[0].menu[0].menu = new dynamic[1];
parameters[0].menu[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].menu[0].title = "Maybe Not";
parameters[0].menu[0].menu[0].id = "8";
parameters[0].menu[0].menu[0].alert = "No";
parameters[0].menu[0].menu[0].menu = new dynamic[0];
parameters[1] = new ExpandoObject();
parameters[1].title = "No";
parameters[1].id = "2";
parameters[1].menu = new dynamic[0];
string json = JsonConvert.SerializeObject(parameters, Formatting.Indented);
Console.WriteLine(json);
Here is the work in fiddle
Note: There are other ways to achieve this, but I have been using this approach.

Categories

Resources