1

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?

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Actually, I tried this and it solves both my problems. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.