title: JSON serialization of an object with a variable length using JsonConvert in .net
body: <p>I need help with some JSON serialization using the .NET/Newtonsoft JsonConvert.SerializeObject method. I have a class which I am using to store the variables that are outbound, called JSONVars. </p>
  
  <p>My question is about how to handle the "Answer" variables in the below sample.</p>
  
  <p>The first and last names always have one return in the loop, so that's easy. However the Answer part could have multiple returns in a loop.</p>
  
  <p>A theoretical outbound JSON string would look like:</p>
  
  <pre><code>{ 
      "FirstName" : "John", 
      "LastName" : "Doe", 
      "FavoriteVacation" : "Beach", 
      "FavoriteState" : "FL" 
      ..... 
  } 
  </code></pre>
  
  <p>with the "..." representing 1 to n possible returns in the loop. </p>
  
  <p>As you can see, the place that I'm sending the JSON string needs to have it all in one comma delimited string that is properly formatted JSON, so I can't send the Answer block as a JSON array, like this (it will fail):</p>
  
  <pre><code>{ 
      "FirstName" : "John", 
      "LastName" : "Doe", 
      "Answers" : [ 
          "FavoriteVacation" : "Beach", 
          "FavoriteState" : "FL" ..... 
  } 
  </code></pre>
  
  <p>How can I adjust this so that I can "add" to the json serialized string 1 to n "answer" blocks? </p>
  
  <p>Here is my code:</p>
  
  <pre><code> public class JSONVars
      {
          public string FirstName;
          public string LastName;
          //??? public string Answer;
      }
  
   static void Main(string[] args)
          {
  
    foreach (var objReturn in objlst)
              {
  
     JSONVars jsonvars = new JSONVars();
     jsonvars.FirstName = objReturn.FirstName;
     jsonvars.LastName = objReturn.LastName;
  
  
  
  foreach (var answerobj in objReturn.SurveyAnswers)
                  {
  
                      if (answerobj.Vacation != null)
                      {
                          foreach (var answerobjVaca in answerobj.Vacation)
                          {
                            //???????
                            //answerobjVaca.QuestionText;
                            //answerobjVaca.AnswerText;
                          }
                      }
                  }
   var jsonHolder = JsonConvert.SerializeObject(jsonvars);
  }
  }
  </code></pre>
  
  <p>The jsonHolder var is what is being sent out to an external service and needs to be properly serialized for JSON transmission.</p>
  
  <p>Please note some code (like how objReturn is populated) left out for brevity.</p>