I am using C# and trying to create a JSON string from a dynamic object.
string jsonObj = string.Empty;
dynamic DetailObj = new ExpandoObject();
foreach (DataRow row in dtDetails.Rows)
{
DetailObj.ID = row["ID"].ToString();
DetailObj.Description = row["Description"].ToString();
DetailObj.ExpDate = row["Date"].ToString();
}
dynamic EmailObj = new ExpandoObject();
foreach (DataRow row in dtReturnData.Rows)
{
EmailObj.ID = row["EmailTypeId"].ToString();
EmailObj.FirstName = row["FirstName"].ToString();
EmailObj.LastName = row["LastName"].ToString();
EmailObj.Details = DetailObj;
EmailObj.Email = row["Email"].ToString();
}
jsonObj = JsonConvert.SerializeObject(EmailObj);
I am trying to get the output string:
[{"ID":"5","FirstName":"Joe","LastName":"Johnson","Details":[{"ID":"1","Description":"Player1","ExpDate":"08/30/2021 00:00:00"}],"Email":"joejohnson@sample.com"}]
But what I am currently getting is:
"{"ID":"5","FirstName":"Joe","LastName":"Johnson","Details":{"ID":"1","Description":"Player1","ExpDate":"08/30/2021 00:00:00"},"Email":"joejohnson@sample.com"}"
The difference between the desired output and current output is the [] at the beginning and end of the entire JSON, instead of the "", as well as the detailobj object within the JSON.
What can I do to change the output?
Additionally, dtDetails contains multiple rows which all need to be passed in the JSON details object. Currently, I am getting a single row that is passed as part of the DetailObj. Is there a way to correct that?