tags:

views:

468

answers:

5

Hi,

I am trying to use the example in this link http://sharpdevpt.blogspot.com/2009/10/deserialize-json-on-c.html?showComment=1265045828773#c2497312518008004159

But my project wont compile using JavaScriptConvert.DeserializeObject, the example says this is from a .net library does anyone know which one?

I know the example below uses Newtonsoft.Json....

+5  A: 

The Javascript Serializer in .NET is part of the System.Web.Script.Serialization namespace.

Here's an example extension method I use to deserialize strings:

public static T FromJSON<T>(this string json)
 {
            JavaScriptSerializer jss = new JavaScriptSerializer();

            return jss.Deserialize<T>(json);
 }
Jamie Dixon
Error 1 The type or namespace name 'Script' does not exist in the namespace 'System.Web' (are you missing an assembly reference?) But I have the System.Web dll
nav
Thanks alot how would I use your method?
nav
The namespace is in `System.Web.Extensions.dll`. A quick MSDN search can find it.
Jeff Yates
+3  A: 

You might also want to have a look at JSON.NET, which is a free, open-source project, and it's both a lot faster than the built-in .NET JSON serializers, and it's also available on .NET 1.x and 2.0, if you still need to support those.

It's quite a marvellous piece of software indeed! Highly recommended.

marc_s
A: 

For a simple way to deserialize http://blogs.msdn.com/rakkimk/archive/2009/01/30/asp-net-json-serialization-and-deserialization.aspx

JavaScriptSerializer js = new JavaScriptSerializer();
Person p2 = js.Deserialize<classtype>(str);
nav
+1  A: 

Hi! The link you posted is from my blog, what's the problem on using it? feel free to reply on the blog post or mail me to [email protected]. I've been using for a while and it works fine.

About the discussed JavascriptSerializer that comes embedded on the .Net Framework, the problem is that this serializer doesn't serialize to/from List<>. If you want to do it you need to use Newtonsoft.JSON to do it, because .NET Framework simply doesn't support it. And since the main use for this is to return JSON to some client-side script, for searching or whatever, the List<> thing is a must.

Ricardo Rodrigues
A: 

But with that piece of code you can't deserialize/serialize List<> which are very handy in case you're handling result sets, and are more performant than .NET's built-in.JavascriptSerializer, so the Newtonsoft.Json is the best option:

For a single object of your custom type:

classtype myDeserializedObj = (classtype)JavaScriptConvert.DeserializeObject(jsonString, typeof(classtype));       

For a List of objects of your custom type:

List<classtype> myDeserializedObjList = (List<classtype>)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString, typeof(List<classtype>));
Ricardo Rodrigues