问题
I have a Silverlight class marked with the ScriptableType & ScriptableMember and I expect to be able to pass the object from Silverlight to javascript. When I call JSON.stringify (in javascript) I expect to receive a JSON representation of the object but all I get is {}
The class is defined as:
[ScriptableType()]
public class MyEvent
{
[ScriptableMember(ScriptAlias = "eventContent")]
public int EventContent { get; set; }
}
I pass the object from Silverlight like this:
var jsonObject = new MyEvent { EventContent = 1 };
HtmlPage.Window.Invoke("publishValue", topic, jsonObject);
And in javascript I'm doing the following:
alert(topic);
alert(jsonObject);
alert(JSON.stringify(jsonObject));
When I use the debugger I only see the jsonObject
as of type Object
but the call alert(jsonObject)
returns the correct type and if I access the property jsonObject.eventContent
I get the correct value back, but it doesn't serialize correctly with JSON.stringify
.
Anyone tell what I'm doing wrong?
I don't want to have to serialize the object in Silverlight before sending to javascript.
Cheers
AWC
回答1:
JSON.stringify
enumerates over enumerable properties of an object using for...in
. If the properties aren't enumerable, they won't be included in the resulting string.
The Silverlight object is an external object, not a native javascript object. Just like an ActiveXObject, the properties are not discoverable/enumerable. I'm not sure if there's a way around this. A couple of pages I found hint towards implementing IEnumerable to be able to iterate using a foreach
in the native language but I'm not sure if this would carry over to JavaScript.
I wouldn't rely on it being possible but you never know. If you require an object to be enumerable, the only way might be to serialize it using System.Json
and call eval
on the document to unserialize it in JavaScript.
回答2:
I've managed to solve the problem!
Instead of declaring an object like this for passing from Silverlight to javascript:
[ScriptableType()]
public class MyEvent
{
[ScriptableMember(ScriptAlias = "eventContent")]
public int EventContent { get; set; }
}
I use the System.Json
namepsace and create a JsonObject
like this:
var ob = new JsonObject
{
{"eventContent", 1}
};
Check out the documentation of System.Json.JsonObject
for more info.
Cheers
AWC
来源:https://stackoverflow.com/questions/2295859/silverlight-passing-json-object-incorrectly