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

New Post: Array as return type

$
0
0
Hi Klator,

It looks like JSON.stringify() can't work with .NET arrays. Each .NET array has a property named SyncRoot that simply returns the array instance. This makes the array a "circular" object and therefore incompatible with JSON.

In general, .NET objects often have lots of methods and other non-data members that make them JSON-unfriendly. Therefore we recommend in this case that you use script arrays instead. You can use something like this to make it dead simple:
public static class ScriptHelpers {
    public static object ToScriptArray<T>(this IEnumerable<T> source, ScriptEngine engine) {
        dynamic array = engine.Evaluate("[]");
        foreach (var element in source) {
            array.push(element);
        }
        return array;
    }
}
and then, in your .NET method:
var s = this.Where(e => e.Text() != "").Select(e => e.Text()).ToScriptArray(engine);
You could also make ToScriptArray() more sophisticated - e.g., it could handle arrays within arrays, it could convert elements to script objects, etc.

Cheers!

Viewing all articles
Browse latest Browse all 2297

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>