This project has moved and is read-only. For the latest updates, please go here.

support serialization with System.Web.Script.Serialization.JavaScriptSerializer

Nov 7, 2008 at 7:27 AM
Edited Nov 7, 2008 at 7:52 AM
I've discovered that JObject serialization with System.Web.Script.Serialization.JavaScriptSerializer is not supported
This is very serious drawback for using in ajax 'scipt methods' (where JavaScriptSerializer called implicitly behind the scenes)
for example:
new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new JObject(new JProperty("test",new JValue("test")))) failed:
"Cannot access child value on Newtonsoft.Json.Linq.JValue."
why JValue must support IEnumerable (via JToken) if it hasn't 'child values'? For what?
At present time (in my script methods) I use something like that:
return new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(new JObject(new JProperty("test",new JValue("test"))).ToString())
to return Dictionary<string,object>. This is NO GOOD. And I don't wanna return string and eval on client.
but I like linq to json, so I see 2 solutions:
- fix JValue serialization with JavaScriptSerializer
- or implement JObject 'casting' to Dictionary<string,object/*Dictionary<string,object> or primitive*/>
Nov 7, 2008 at 11:18 PM
To make LINQ nice to work with JToken, which most members return, has to implement IEnumerable. If it doesn't you end up with casts everywhere. The downside is the JValue ends up implementing IEnumerable.

If you want to return JObject from a script method like that you could create a JavaScriptConverter for serializing and deserializing JObject, JArray, JValue, etc, and then register it in ScriptingJsonSerializationSection. If you do do this I would love to get a copy of the code to include in Json.NET

~ James
Nov 10, 2008 at 6:57 AM
OK I'll try soon