0

I have simple C# object instantiated like

User theUser = new User("John", "Doe");

now I need to load it to my Node.js file like:

var theUser = {name:"John", lastName:"Doe"};

Can you please let me know how to do that? Do I have to save/write the output on a separate json file? or..?

Thanks

Behseini
  • 6,066
  • 23
  • 78
  • 125
  • What do you mean by "load it" to your Node.js file? – DavidG May 26 '16 at 21:43
  • Hi David I have a server side Javascript which is suppose to send the following data to another server using node and Ajax , I hope this was helpful! – Behseini May 26 '16 at 21:45
  • It seems like an odd step to convert to JS for Node when C# can send it to the other server directly. – DavidG May 26 '16 at 21:46

2 Answers2

1

If you intend to use JSON as bridge from C# to Nodejs, use JavaScriptSerializer class to convert your C# class as JSON data.

https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

C#

// your data class
public class YourClassName
{
    ...
}

// Javascript serialization
using System.IO;
using System.Web.Script.Serialization;

String json = new JavaScriptSerializer().Serialize(YourClassName);
File.WriteAllText("json_file_path", json);

Node.js

// Async mode
var jsondata = require('fs').readFile('json_file_path', 'utf8', function (err, data) {
    if (err) throw err; // throw error if not found or invalid
    var obj = JSON.parse(jsondata);
});

// Sync mode
var jsondata = JSON.parse(require('fs').readFileSync('json_file_path', 'utf8'));

Node.js reference: How to parse JSON using Node.js?

Hopefully this is useful, CMIIW.

Community
  • 1
  • 1
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
0

Why not just use Newtonsoft.Json - add a reference to this within your project.

To convert the object from a known type to json string;

string output = JsonConvert.SerializeObject(theUser);

To convert the object to a dynamic type;

dynamic json = JToken.Parse(theUser); - to dynamic

MSDN Link for extra help, if needed.

Hexie
  • 3,955
  • 6
  • 32
  • 55