Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing from JSON (ScriptObject) to Managed Object

I'm attempting to deserialize json returned from javascript via Silverlight.

Basically on the client side I am returning JSON and in my C# handler, I am getting it via ScriptObject...

I tried the ConvertTo method on the ScriptObject and still could not get anything.

How would I be able to convert a ScriptObject into a C# object that is a list of objects?

SomeCallBack(ScriptObject result) {

    // convert to managed object

    var objects = result.ConvertTo<List<SomeObjectClass>>(); // can't get any property from it..

    // however the count is correct...
    MessageBox.Show("count: " + objects.Count); // shows correct count of items
}
like image 348
LB. Avatar asked Feb 21 '26 05:02

LB.


1 Answers

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);
like image 198
AnthonyWJones Avatar answered Feb 23 '26 18:02

AnthonyWJones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!