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":"[email protected]"}]
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":"[email protected]"}"
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?
The problem is that you are overwriting the value of all these fields as you iterate through. What you want to do is to have an list of dynamic objects. for example:
List<dynamic> EmailObj = new List<ExpandoObject>();
foreach (DataRow row in dtReturnData.Rows)
{
var item = new ExpandoObject();
item.ID = row["EmailTypeId"].ToString();
item.FirstName = row["FirstName"].ToString();
item.LastName = row["LastName"].ToString();
item.Details = DetailObj;
item.Email = row["Email"].ToString();
EmailObj.Add(item);
}