converting list to json format - quick and easy way

Viewed 160411

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.

8 Answers

You could return the value using return JsonConvert.SerializeObject(objName); And send it to the front end

If you are using WebApi, HttpResponseMessage is a more elegant way to do it

public HttpResponseMessage Get()
{
    return Request.CreateResponse(HttpStatusCode.OK, ListOfMyObject);
}
Related