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

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

3
  • What do you mean by "load it" to your Node.js file? Commented May 26, 2016 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! Commented May 26, 2016 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. Commented May 26, 2016 at 21:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.