Behseini
Behseini

Reputation: 6330

How to Convert C# Values to Node.js Object

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"};

How can I do that? Do I have to save/write the output on a separate JSON file?

Upvotes: 0

Views: 1689

Answers (2)

Hexie
Hexie

Reputation: 4221

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.

Upvotes: 0

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

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.

Upvotes: 1

Related Questions