Deserializing from JSON (ScriptObject) to Managed Object Deserializing from JSON (ScriptObject) to Managed Object json json

Deserializing from JSON (ScriptObject) to Managed Object


Silverlight contains no API to take a ScriptObject and serialise to a JSON string.

Silverlight supports JSON serialisation via the System.Runtime.Serialization.Json.DataContractJsonSerializer class found in the System.ServiceModel.Web dll.

You will need to get some javascript base JSON serialiser to convert the value you are trying to pass as a ScriptObject so that you pass a JSON string parameter instead of a ScriptObject. I believe the popular tool for this job is JQuery.

Now it looks like you were expecting a set (JSON like "[x1,x2,,,xn]") where x items are of type SomeObjectClass. You can use this little generic function to deserialise such a list :-

    List<T> DeserializeJSON<T>(string json)    {        byte[] array = Encoding.UTF8.GetBytes(json);        MemoryStream ms = new MemoryStream(array);        DataContractJsonSerializer dcs = new DataContractJsonSerializer(typeof(List<T>));        return (List<T>)dcs.ReadObject(ms);    }

You would do:-

 var objects = DeserializeJSON<SomeObjectClass>(someJSON);


http://json.codexplex.com/

They have a silverlight version, sounds like the Newtonsoft.Json.Linq.JObject is what you're after.


If you are returning an actual JSON object, then you can actually use the ScriptObject.ConvertTo method to deserialize the JSON object directly into a C# object. For example, you could do:

JSON Object

{ id: 0001,  name: 'some_name',  data: [0.0, 1.0, 0.9, 90.0] }

C# Object

using System.Runtime.Serialization;  // From the System.Runtime.Serialization assembly[DataContract]public struct JsonObj{    [DataMember]    public int id;    [DataMember]    public string name;    [DataMember]    public double[] data;}

C# Callback

public void SomeCallback(ScriptObject rawJsonObj){    // Convert the object    JsonObj jsonObj = rawJsonObj.ConvertTo<JsonObj>();}

However, if you are returning a string that represents the JSON object, as opposed to an actual JSON object, then this will not work and you will have to use an alternate deserialization method. Refer to MSDN for more details.

Hope this helps.