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
-
8MS now ship NewtonSoft as standard in the VS MVC4 project template Commented Oct 21, 2013 at 8:26
-
64You can also serialize anonymous objects when needed:
string json = JsonConvert.SerializeObject(new { "PropertyA" = obj.PropertyA });
. Commented May 6, 2014 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"
bePropertyA
?– JonahCommented Jul 18, 2016 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!– VassilisCommented Jul 5, 2017 at 16:19
-
13@MattBeckman @Jonah is
string json = JsonConvert.SerializeObject(new { PropertyA = obj.PropertyA });
without double quotes onPropertyA.
– JoseCommented Jan 11, 2019 at 12:28
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();
-
yea, just trying to figure out how to form the JSON text first. Thanks Commented Jun 29, 2009 at 0:37
-
-
2JavaScriptSerializer is part of ASP.NET Ajax 1.0 if you want to use it from .NET 2.0. Commented Jun 29, 2009 at 0:58
-
2You can still use it. Its part of the ASP.NET 2.0 AJAX Extensions 1.0: asp.net/AJAX/Documentation/Live/mref/…– NarenCommented Jun 29, 2009 at 1: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? Commented Jun 29, 2009 at 1:42
Simple 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"
};
// Transform 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"]);
-
-
was really looking for something as simple as in PHP. Thanks!– ArisCommented Mar 24, 2021 at 18:28
This library is very good for JSON from C#
-
1Let me ask, what are the benefits to using this framework vs. just that helper method that CMS mentioned above? Commented Jun 29, 2009 at 0:44
-
1allows you finer granularity over the json e.g you can specify to include nulls or not etc Commented Jun 29, 2009 at 0: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());
}
}
-
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. Commented Jul 8, 2009 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!
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.
-
I tried JsonSerializer.SerializeToString with a list of objects and it just returned empty json: "[{},{}]" pastebin.com/yEw57L3T Here's what my object looks like before I call SerializeToString i.imgur.com/dYIE7J1.png The top voted answer on here worked though, returning what I expected: pastebin.com/aAtB3Gxu Commented Oct 25, 2013 at 4:05
-
1fastest .NET JSON serializer link is dead.– user1108948Commented Feb 2, 2016 at 21:13
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.
Take a look at http://www.codeplex.com/json/ for the json-net.aspx project. Why re-invent the wheel?
-
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. Commented Jun 29, 2009 at 0: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.
-
1i have tried the JavaScriptSerializer and it does not work well with null objects.– Luke101Commented Jun 29, 2010 at 1: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) Commented Jun 29, 2010 at 9: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.
-
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" Commented Jun 29, 2009 at 0: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"
]
]
]
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.
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}]}
-
url: "getData.asmx/GetLatLon", as I expect GetLatLon method in your server side code. But there is not.– LaliCommented Nov 11, 2014 at 8:07
Include:
using System.Text.Json;
Then serialize your object_to_serialize like this: JsonSerializer.Serialize(object_to_serialize)