tags:

views:

6049

answers:

8

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?

A: 

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.

Eduardo Scoz
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"
CoffeeAddict
+23  A: 

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();
CMS
yea, just trying to figure out how to form the JSON text first. Thanks
CoffeeAddict
I see, pass your object in
CoffeeAddict
what if you're not using .NET 3.5! da** it
CoffeeAddict
JavaScriptSerializer is part of ASP.NET Ajax 1.0 if you want to use it from .NET 2.0.
Joe Chung
You 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
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?
CoffeeAddict
So cool! Thanks CMS!
jessegavin
+5  A: 

This library is very good for JSON from C#

http://james.newtonking.com/pages/json-net.aspx

Hugoware
thanks I will check this out.
CoffeeAddict
Let me ask, what are the benefits to using this framework vs. just that helper method that CMS mentioned above?
CoffeeAddict
allows you finer granularity over the json e.g you can specify to include nulls or not etc
redsquare
+2  A: 

Take a look at http://www.codeplex.com/json/ for the json-net.aspx project. Why re-invent the wheel?

Josh
depends, 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.
CoffeeAddict
+3  A: 

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.

DrJokepu
i have tried the JavaScriptSerializer and it does not work well with null objects.
Luke101
@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)
DrJokepu
A: 

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.

Steve
+1  A: 

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());
    }
}
Joe Chung
So ... 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
A: 

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.

mythz