newtonsoft - convert nested list to json c#

converting list to json format-quick and easy way (4)

3 years of experience later, I've come back to this question and would suggest to write it like this:

string output = new JavaScriptSerializer().Serialize(ListOfMyObject);

One line of code.

Let's say I have an object MyObject that looks like this:

public class MyObject
  int ObjectID {get;set;}
  string ObjectString {get;set;}

I have a list of MyObject and I'm looking to convert it in a json string with a stringbuilder. I know how to create a JavascriptConverter and create a json string by passing a list and having the converter build the string but in this particular case I'm looking to avoid the overhead and go straight to a json string with a foreach loop on the list like this:

StringBuilder JsonString = new StringBuilder();

foreach(MyObject TheObject in ListOfMyObject)


I've tried to use this method by appending with commas and quotes but it hasn't worked out (yet).

Thanks for your suggestions.

For me, it worked to use Newtonsoft.Json:

using Newtonsoft.Json;
// ...
var output = JsonConvert.SerializeObject(ListOfMyObject);

I've done something like before using the JavaScript serialization class:

using System.Web.Script.Serialization;


JavaScriptSerializer jss = new JavaScriptSerializer();

string output = jss.Serialize(ListOfMyObject);