Skip to content

Navigation Menu

Sign up

Using Jsonix in Node.js Programs

Alexey Valikov edited this page Sep 4, 2015 · 2 revisions

Using Jsonix in Node.js Programs

Adding Jsonix to package.json

To use Jsonix with node.js you will first need to add it as dependency in your package.json:

{
 "name": "mypackage",
 "..." : "...",
 "dependencies": {
 "jsonix": "~<VERSION>",
 "..." : "...",
 }
}

If you wish also to compile your schema during the build, also add jsonix-schema-compiler as dependency and configure compilation in prepublish:

{
 "name": "mypackage",
 "..." : "...",
 "dependencies": {
 "jsonix": "~<VERSION>",
 "jsonix-schema-compiler": "~<VERSION>",
 "..." : "..."
 },
 "scripts" : {
 "prepublish" : "java -jar node_modules/jsonix-schema-compiler/lib/jsonix-schema-compiler-full.jar -d mappings mySchema.xsd -b bindings.xjb",
 "..." : "..."
 }
}

See Jsonix Schema Compiler - NPM Usage for mor information.

Using Jsonix in your Node.js code

Once you've added Jsonix as a dependency, you can now require it in your node.js code:

var Jsonix = require('jsonix').Jsonix;

You will also need to required your mappings. Assuming you have generated mappings for you schema in mappings/MySchema.js file:

var MySchema = require('../mappings/MySchema').MySchema;

Now you're ready to create Jsonix context, use it to construct marshallers and unmarshallers and use the to parse and serialize JSON from/to XML:

var context = new Jsonix.Context([ MySchema ]);
var unmarshaller = context.createUnmarshaller();
		
// Unmarshal the XML file
unmarshaller.unmarshalFile( 'my.xml',
	function(myElement) {
		var myData = myElement.value;
		// ...
	});
var myNewElement = {
	// ...
};
var marshaller = context.createMarshaller();
console.log(marshaller.marshalString(myNewElement));

Clone this wiki locally

AltStyle によって変換されたページ (->オリジナル) /