0

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?

1 Answer 1

2

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);
}
2
  • Thank you. Do you know how I could change the output JSON from what I am getting right now to what I am trying to get as shown above?
    – HaaroWalo
    Mar 10, 2021 at 20:20
  • Actually, I tried this and it solves both my problems. Thank you!
    – HaaroWalo
    Mar 11, 2021 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.