11

I've found ScriptingJsonSerializationSection but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it on the fly with the <System.Web.Services.WebMethod()> and <System.Web.Script.Services.ScriptMethod()> attributes so there must be a built-in way that I'm missing.

PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it.

travis
  • 35,751
  • 21
  • 71
  • 94
  • "using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it" - well, that "2.0" could be interpreted as "not 1.1" instead of "not 3.x". – bzlm Mar 02 '09 at 12:58

6 Answers6

11

This should do the trick

Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer
Dim jsonString as String = jsonSerialiser.Serialize(yourObject)
TonyB
  • 3,882
  • 2
  • 25
  • 22
6

I think what you're looking for is this class:

System.ServiceModel.Web.DataContractJsonSerializer

Here's an example from Rick Strahl: DataContractJsonSerializer in .NET 3.5

Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
Joseph Kingry
  • 8,188
  • 4
  • 36
  • 52
4

Since the JavaScriptSerializer class is technically being deprecated, I believe DataContractJsonSerializer is the preferable way to go if you're using 3.0+.

Dave Ward
  • 59,815
  • 13
  • 117
  • 134
3

Well, I am currently using the following extension methods to serialize and deserialize objects:

using System.Web.Script.Serialization;

public static string ToJSON(this object objectToSerialize)
{
  JavaScriptSerializer jss = new JavaScriptSerializer();
  return jss.Serialize(objectToSerialize);
}

/// <typeparam name="T">The type we are deserializing the JSON to.</typeparam>
public static T FromJSON<T>(this string json)
{
  JavaScriptSerializer jss = new JavaScriptSerializer();
  return jss.Deserialize<T>(json);
}

I use this quite a bit - be forewarned, this implementation is a bit naive (i.e. there are some potential problems with it, depending on what you are serializing and how you use it on the client, particularly with DateTimes).

Jason Bunting
  • 58,249
  • 14
  • 102
  • 93
2

In the System.Web.Extensions assembly, version 3.5.0.0, there's a JavaScriptSerializer class that should handle what you want.

Jarrod Dixon
  • 15,727
  • 9
  • 60
  • 72
1

Try

System.Web.Script.Serialization.JavaScriptSerializer

or Check out JSON.org there is a whole list of libraries written to do exactly what you want.

Steven Williams
  • 1,014
  • 1
  • 10
  • 16