I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the JSON string and them format your response as JSON?
15 Answers
Using Newtonsoft.Json makes it really easier:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
Documentation: Serializing and Deserializing JSON

- 48,174
- 24
- 109
- 130

- 4,740
- 3
- 28
- 31
-
8MS now ship NewtonSoft as standard in the VS MVC4 project template – Chris F Carroll Oct 21 '13 at 08:26
-
62You can also serialize anonymous objects when needed: ``string json = JsonConvert.SerializeObject(new { "PropertyA" = obj.PropertyA });``. – Matt Beckman May 06 '14 at 22:22
-
11@MattBeckman I get "Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. Shouldn't `"PropertyA"` be `PropertyA`? – Jonah Jul 18 '16 at 13:40
-
3So we need to implement a Class and objects, to construct a simple json! Imagine nested - not fixed arrays - elements. I can't see why so much enthusiasm in the air! – Vassilis Jul 05 '17 at 16:19
-
@VassilisGr to my opinion it's much safer and better to construct the classes and instantiate them, it keeps your API clearer and documented. There are other ways to create JSON strings "on the fly" however, if that's what you prefer. – Orr Jul 07 '17 at 18:03
-
12@MattBeckman @Jonah is `string json = JsonConvert.SerializeObject(new { PropertyA = obj.PropertyA });` without double quotes on `PropertyA.` – Jose Jan 11 '19 at 12:28
-
What is Product? I get this message "The type or namespace name 'Product' could not be found" – Hneel Jun 10 '22 at 14:02
You could use the JavaScriptSerializer class, check this article to build an useful extension method.
Code from article:
namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
Usage:
using ExtensionMethods;
...
List<Person> people = new List<Person>{
new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
};
string jsonString = people.ToJSON();

- 28,047
- 29
- 99
- 127

- 807,428
- 183
- 922
- 838
-
yea, just trying to figure out how to form the JSON text first. Thanks – PositiveGuy Jun 29 '09 at 00:37
-
-
2JavaScriptSerializer is part of ASP.NET Ajax 1.0 if you want to use it from .NET 2.0. – Joe Chung Jun 29 '09 at 00:58
-
2You can still use it. Its part of the ASP.NET 2.0 AJAX Extensions 1.0: http://www.asp.net/AJAX/Documentation/Live/mref/T_System_Web_Script_Serialization_JavaScriptSerializer.aspx – Naren Jun 29 '09 at 01:10
-
our project can open in VS 2008...so it was converted at some point. Does that mean we can now use .NET 3.5 within our existing codebase? – PositiveGuy Jun 29 '09 at 01:42
-
@CMS: i tried the above stuff and am getting Empty Json String as : [{},{}] my list is like this : List
people = new List – pvaju896 Aug 23 '11 at 07:17{ new Person{age = 1, name = "Scott"}, new Person{age = 2, name = "Bill"} }; -
To use you must add the assembly reference to your project to System.Web.Extensions.dll – George Filippakos Aug 25 '13 at 12:33
-
There is an error in the code, it should be "Guthrie", not "Gurthie" ;-) – Culme Jul 26 '18 at 09:48
Simlpe use of Newtonsoft.Json and Newtonsoft.Json.Linq libraries.
//Create my object
var myData = new
{
Host = @"sftp.myhost.gr",
UserName = "my_username",
Password = "my_password",
SourceDir = "/export/zip/mypath/",
FileName = "my_file.zip"
};
//Tranform it to Json object
string jsonData = JsonConvert.SerializeObject(myData);
//Print the Json object
Console.WriteLine(jsonData);
//Parse the json object
JObject jsonObject = JObject.Parse(jsonData);
//Print the parsed Json object
Console.WriteLine((string)jsonObject["Host"]);
Console.WriteLine((string)jsonObject["UserName"]);
Console.WriteLine((string)jsonObject["Password"]);
Console.WriteLine((string)jsonObject["SourceDir"]);
Console.WriteLine((string)jsonObject["FileName"]);

- 1,001
- 7
- 7
This library is very good for JSON from C#

- 35,731
- 24
- 60
- 70
-
1Let me ask, what are the benefits to using this framework vs. just that helper method that CMS mentioned above? – PositiveGuy Jun 29 '09 at 00:44
-
1allows you finer granularity over the json e.g you can specify to include nulls or not etc – redsquare Jun 29 '09 at 00:52
This code snippet uses the DataContractJsonSerializer from System.Runtime.Serialization.Json in .NET 3.5.
public static string ToJson<T>(/* this */ T value, Encoding encoding)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream())
{
using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
{
serializer.WriteObject(writer, value);
}
return encoding.GetString(stream.ToArray());
}
}

- 11,955
- 1
- 24
- 33
-
3So ... uncomment the 'this' reference to actually get this snippet working. If you haven't worked with extension methods before, this might not be obvious. – Dan Esparza Jul 08 '09 at 21:19
If you need complex result (embedded) create your own structure:
class templateRequest
{
public String[] registration_ids;
public Data data;
public class Data
{
public String message;
public String tickerText;
public String contentTitle;
public Data(String message, String tickerText, string contentTitle)
{
this.message = message;
this.tickerText = tickerText;
this.contentTitle = contentTitle;
}
};
}
and then you can obtain JSON string with calling
List<String> ids = new List<string>() { "id1", "id2" };
templateRequest request = new templeteRequest();
request.registration_ids = ids.ToArray();
request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");
string json = new JavaScriptSerializer().Serialize(request);
The result will be like this:
json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"
Hope it helps!

- 612
- 7
- 7
You can also try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContracts, any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.
Basic Example
var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json);
Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.

- 141,670
- 29
- 246
- 390
-
I tried JsonSerializer.SerializeToString with a list of objects and it just returned empty json: "[{},{}]" http://pastebin.com/yEw57L3T Here's what my object looks like before I call SerializeToString http://i.imgur.com/dYIE7J1.png The top voted answer on here worked though, returning what I expected: http://pastebin.com/aAtB3Gxu – Matthew Lock Oct 25 '13 at 04:05
-
1
If you want to avoid creating a class and create JSON then Create a dynamic Object and Serialize Object.
dynamic data = new ExpandoObject();
data.name = "kushal";
data.isActive = true;
// convert to JSON
string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
Read the JSON and deserialize like this:
// convert back to Object
dynamic output = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
// read a particular value:
output.name.Value
ExpandoObject
is from System.Dynamic
namespace.

- 3,265
- 1
- 26
- 29
Take a look at http://www.codeplex.com/json/ for the json-net.aspx project. Why re-invent the wheel?

- 590
- 3
- 4
-
3depends, I may not want to rely on a 3rd party open source plugin just to create JSON. Would rather create the string/helper method myself. – PositiveGuy Jun 29 '09 at 00:41
If you can't or don't want to use the two built-in JSON serializers (JavaScriptSerializer and DataContractJsonSerializer) you can try the JsonExSerializer library - I use it in a number of projects and works quite well.

- 118,853
- 40
- 150
- 176
-
1i have tried the JavaScriptSerializer and it does not work well with null objects. – Luke101 Jun 29 '10 at 01:36
-
1@Luke101: How exactly? I mean I use it everyday and never had problems, so I'm honestly curious! (no irony, I'm really curious because I've never encountered problems) – Tamas Czinege Jun 29 '10 at 09:36
If you're trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:
http://www.asp.net/learn/ajax/tutorial-05-cs.aspx
It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.

- 24,653
- 6
- 47
- 62
-
it would just be a call to an .ashx that would return a string of JSON. First, I'm just trying to figure out how to form the string..use a StringBuilder? Second then yea, how to serialize. When returning XML you'd just set the response's conten t type I think: context.Response.ContentType = "text/xml" – PositiveGuy Jun 29 '09 at 00:39
Encode Usage
Simple object to JSON Array EncodeJsObjectArray()
public class dummyObject
{
public string fake { get; set; }
public int id { get; set; }
public dummyObject()
{
fake = "dummy";
id = 5;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
sb.Append(id);
sb.Append(',');
sb.Append(JSONEncoders.EncodeJsString(fake));
sb.Append(']');
return sb.ToString();
}
}
dummyObject[] dummys = new dummyObject[2];
dummys[0] = new dummyObject();
dummys[1] = new dummyObject();
dummys[0].fake = "mike";
dummys[0].id = 29;
string result = JSONEncoders.EncodeJsObjectArray(dummys);
Result: [[29,"mike"],[5,"dummy"]]
Pretty Usage
Pretty print JSON Array PrettyPrintJson() string extension method
string input = "[14,4,[14,\"data\"],[[5,\"10.186.122.15\"],[6,\"10.186.122.16\"]]]";
string result = input.PrettyPrintJson();
Results is:
[
14,
4,
[
14,
"data"
],
[
[
5,
"10.186.122.15"
],
[
6,
"10.186.122.16"
]
]
]

- 177
- 1
- 8
The DataContractJSONSerializer will do everything for you with the same easy as the XMLSerializer. Its trivial to use this in a web app. If you are using WCF, you can specify its use with an attribute. The DataContractSerializer family is also very fast.

- 11,763
- 15
- 70
- 103
I've found that you don't need the serializer at all. If you return the object as a List. Let me use an example.
In our asmx we get the data using the variable we passed along
// return data
[WebMethod(CacheDuration = 180)]
public List<latlon> GetData(int id)
{
var data = from p in db.property
where p.id == id
select new latlon
{
lat = p.lat,
lon = p.lon
};
return data.ToList();
}
public class latlon
{
public string lat { get; set; }
public string lon { get; set; }
}
Then using jquery we access the service, passing along that variable.
// get latlon
function getlatlon(propertyid) {
var mydata;
$.ajax({
url: "getData.asmx/GetLatLon",
type: "POST",
data: "{'id': '" + propertyid + "'}",
async: false,
contentType: "application/json;",
dataType: "json",
success: function (data, textStatus, jqXHR) { //
mydata = data;
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log(xmlHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
}
});
return mydata;
}
// call the function with your data
latlondata = getlatlon(id);
And we get our response.
{"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}

- 1,051
- 3
- 17
- 42
-
url: "getData.asmx/GetLatLon", as I expect GetLatLon method in your server side code. But there is not. – Lali Nov 11 '14 at 08:07
Include:
using System.Text.Json;
Then serialize your object_to_serialize like this: JsonSerializer.Serialize(object_to_serialize)

- 61
- 1
- 5