Reputation: 47743
how can you serialize an object to JSON in .NET 2.0 using C#?
Upvotes: 14
Views: 33163
Reputation: 1519
I was able to backport Mono's implementation of System.Json to C# 2.0 with a few minor changes.
You'll need 6 files from here or you can simply download my C# 2.0 project from here.
Note that with System.Json you'll have to manually serialize any non-primitive data type. (see here)
Upvotes: 1
Reputation: 522
I use below code for JSON message and works well for me.
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
}
Calling JSON serializer in WCF.
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json)]
public string LoadDetails()
{
LogDetails objSubLog = new LogDetails ();
List<LogDetails> lstLogdetails;
DAL objDAL = new DAL();
lstLogdetails = objDAL.GetLog("ALL", objSubLog);
return lstLogdetails.ToJSON();
}
Upvotes: -1
Reputation:
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();
}
}
}
Upvotes: 1
Reputation: 24299
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.
Upvotes: 1
Reputation: 12123
You can use the JavaScriptSerializer class from ASP.NET Ajax 1.0, which is compatible with .NET 2.0.
Upvotes: 11