Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: Pass Javascript Object with Array to the host

0
0
Hi again,

One thing you could do is modify your Test class so that it converts arrays before passing them to Json.NET:
publicclass Test {
    privatereadonly V8Converter v8Converter = new V8Converter();
    publicvoid Output(object o) {
        Console.WriteLine(JsonConvert.SerializeObject(o, v8Converter));
    }
    privateclass V8Converter : JsonConverter {
        publicoverridebool CanConvert(Type type) {
            return type.Name == "V8ScriptItem";
        }
        publicoverridevoid WriteJson(JsonWriter w, object o, JsonSerializer ser) {
            dynamic dynObj = o;
            if (dynObj.constructor.name == "Array") {
                var length = (int)dynObj.length;
                var array = Enumerable.Range(0, length).Select(i => dynObj[i]).ToArray();
                ser.Serialize(w, array);
            } else {
                var names = (IEnumerable<string>)dynObj.GetDynamicMemberNames();
                var dictionary = names.ToDictionary(name => name, name => dynObj[name]);
                ser.Serialize(w, dictionary);
            }
        }
        publicoverrideobject ReadJson(JsonReader r, Type type, object o, JsonSerializer ser) {
            thrownew NotImplementedException();
        }
    }
}
Checking the script item type this way is a bit hacky, but it works :)

Good luck!

Viewing all articles
Browse latest Browse all 2297