I'm attempting to transform the result of an arbitrary REST call to via an arbitrary function within a C# project. I think that Edge.js should be able to do what I need; however, I am having trouble getting it to understand a JSON object/array.
From the documentation: Edge.js can marshal any JSON-serializable value between .NET and Node.js (although JSON serialization is not used in the process).
However, what do you do if you have a JSON string, or a Newtonsoft JToken to start with?
My test code below (C#):
List<Dictionary<string, object>> dlist = new List<Dictionary<string, object>>()
{
new Dictionary<string, object>
{
{"a", "abc" },
{"b", "def" }
},
new Dictionary<string, object>
{
{"a", "ghi" },
{"b", "jkl" }
},
new Dictionary<string, object>
{
{"a", "mno" },
{"b", "pqr" }
},
new Dictionary<string, object>
{
{"a", "stu" },
{"b", "vwx" }
}
};
var createHttpServer = Edge.Func(@"
var http = require('http');
return function (port, cb) {
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify([
{a:'abc',b:'def'},
{a:'ghi',b:'jkl'},
{a:'mno',b:'qrs'},
{a:'tuv',b:'wxy'}
]));
}).listen(port, function (error) {
cb(error, function (data, cb) {
server.close();
cb();
});
});
};
");
Func<object, Task<object>> closeHttpServer = (Func<object, Task<object>>)await createHttpServer(8080);
string stringResponse = await new WebClient().DownloadStringTaskAsync("http://localhost:8080");
JToken jsonResponse = JToken.Parse(stringResponse);
Func<object, Task<object>> mapArrayToA = Edge.Func(@"var _prog = function(x) { return x.map(a => a.b).join('-'); }; return function(x, cb) { cb(null, _prog(x)); }");
var dictListResult = await mapArrayToA(dlist);
//var stringResponseResult = await mapArrayToA(stringResponse);
var jsonResponseResult = await mapArrayToA(jsonResponse);
await closeHttpServer(null);
Console.WriteLine(dictListResult);
Console.WriteLine(jsonResponseResult);
The hardcoded List has no problem; Edge returns "def-jkl-pqr-vwx" as expected. The string version is commented out, as Edge fails to find the function "map" on it, and throws an error. The last one with the JToken returns "---" as it identifies an array of objects, but finds no content in it.
What is the best way to pass JSON data to Edge from C#?
via BM-
No comments:
Post a Comment