43

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.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • Note that in a WPF project, you need to add a reference to `System.Web.Extensions` to use `System.Web.Script.Serialization`: https://stackoverflow.com/a/18746092/1599699 https://stackoverflow.com/a/19299695/1599699 – Andrew Jun 28 '18 at 14:44

8 Answers8

59

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

using System.Web.Script.Serialization;

And:

JavaScriptSerializer jss = new JavaScriptSerializer();

string output = jss.Serialize(ListOfMyObject);
Response.Write(output);
Response.Flush();
Response.End();
Mark Ursino
  • 31,209
  • 11
  • 51
  • 83
52

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.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • 5
    I am so glad to see answers like this. That year, we were just confused kids. Years later, things formerly seems so important and hard to us became so easy and inessential, because we grows, however, problems still the same :-) – armnotstrong Feb 13 '15 at 04:06
35

For me, it worked to use Newtonsoft.Json:

using Newtonsoft.Json;
// ...
var output = JsonConvert.SerializeObject(ListOfMyObject);
user8128167
  • 6,929
  • 6
  • 66
  • 79
7

I would avoid rolling your own and use either:

System.Web.Script.JavascriptSerializer

or

JSON.net

Both will do an excellent job :)

Alastair Pitts
  • 19,423
  • 9
  • 68
  • 97
  • 1
    @MatthewT.Baker I don't think that's correct. It's under an MIT license (http://json.codeplex.com/license), so it doesn't cost anything. – Alastair Pitts Aug 19 '15 at 23:48
  • Odd as the [Newtonsoft store](http://www.newtonsoft.com/store) states differently. Unless I'm miss understanding the licensing terms? – ᴍᴀᴛᴛ ʙᴀᴋᴇʀ Aug 20 '15 at 10:16
  • 1
    @MatthewT.Baker That appears to be for [Json.NET Schema](http://www.newtonsoft.com/jsonschema), which is different to the core [Json.NET](http://www.newtonsoft.com/json). – Alastair Pitts Aug 20 '15 at 23:50
2

why reinvent the wheel? use microsoft's json serialize or a 3rd party library such as json.NET

David Wick
  • 7,055
  • 2
  • 36
  • 38
2

I prefer using linq-to-json feature of JSON.NET framework. Here's how you can serialize a list of your objects to json.

List<MyObject> list = new List<MyObject>();

Func<MyObject, JObject> objToJson =
    o => new JObject(
            new JProperty("ObjectId", o.ObjectId), 
            new JProperty("ObjectString", o.ObjectString));

string result = new JObject(new JArray(list.Select(objToJson))).ToString();

You fully control what will be in the result json string and you clearly see it just looking at the code. Surely, you can get rid of Func<T1, T2> declaration and specify this code directly in the new JArray() invocation but with this code extracted to Func<> it looks much more clearer what is going on and how you actually transform your object to json. You can even store your Func<> outside this method in some sort of setup method (i.e. in constructor).

Dmitrii Lobanov
  • 4,897
  • 1
  • 33
  • 50
  • 2
    I agree with this methodology because often the only information needed from a custom object is an ID and a label. However, I would like to point out the code above generates an error. The JObject wrapping the JArray is unnecessary and throws an error of "Can not add Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JObject." – David Jul 28 '15 at 18:16
1

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

Priyanka Arora
  • 409
  • 4
  • 10
1

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

public HttpResponseMessage Get()
{
    return Request.CreateResponse(HttpStatusCode.OK, ListOfMyObject);
}
Daniel Loudon
  • 799
  • 3
  • 18
Spike433
  • 51
  • 4