tags:

views:

1777

answers:

5

how can you serialize an object to JSON in .NET 2.0 using C#?

+4  A: 

Did you try JSON.net ?

J-16 SDiZ
would like to sort of create a helper method like you can in .NET 3.5 obviously I don't have the library Scott mentions here but would like to roll my own. I guess that would be easier said than done:http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx
CoffeeAddict
What do you mean? It IS really easy...
jfar
at work we are stuck with .net 2.0 and I use json.net, works well.
Jeremy B.
Json.NET 1.3 works on .NET 2.0.
James Newton-King
A: 

JSON.org has references to a number of serializers in a number of languages, including more than half a dozen in C#. You should be able to find one which meets your API and licensing needs including JSONsharp with the LGPL license and the well-designed Json.NET.

If what you're serializing is fairly simple, it's not all that hard to write your own for a specific purpose. The JSON.org site has the syntax, and it's very straight-forward.

lavinio
can't use Json.NET, it requires .NET 3.5 SP1.
CoffeeAddict
The JSONsharp should be what you want. It's LGPL, includes source, has an obtion to take an object and serialize it, and requires only .Net 2.0.
lavinio
+2  A: 

You can use the JavaScriptSerializer class from ASP.NET Ajax 1.0, which is compatible with .NET 2.0.

Joe Chung
would rather not install that framework as I'm not using ASP.NET AJAX controls. We use jQuery
CoffeeAddict
It's a server-side class. You don't have to use the client-side code to use that class.
Joe Chung
yea, I know. You might have sold me here since we don't have .NET 3.5
CoffeeAddict
I wonder if that's the same class used in .NET 3.5
CoffeeAddict
where can I get just the assembly? I think I have to install AJAX 1.0 and then grab it right?
CoffeeAddict
so are you saying use the AjaxControlToolkit.dll?
CoffeeAddict
wait, our web project was converted and we're opening it in VS 2008...does that mean we can use .NET 3.5?
CoffeeAddict
+1  A: 

Are you trying to build an RPC server in the .NET side? If so look at Jayrock (jayrock.berlios.de). You get the source code and it will compile under 2.0.

Also setting an RPC server is a snap:

using Jayrock; using Jayrock.JsonRpc; using Jayrock.JsonRpc.Web; using Jayrock.Json; using Jayrock.Json.Conversion;

namespace myRPCService { [JsonRpcService("Service")] public class Service : JsonRpcHandler {

    [JsonRpcMethod("call", Idempotent = true)]
    public string call(string value)
    {
        JsonObject oJSON = JsonConvert.Import(typeof(JsonObject), value) as JsonObject;
       ...
       return oJSON.ToString();
    }
}

}

just trying to return JSON via a call to our .ashx page
CoffeeAddict
A: 

Use the DataContractJsonSerializer class. Like this:

http://www.west-wind.com/WebLog/posts/218001.aspx

Edit: Oh, you are asking about .NET 2.0. Sorry.

Fantius