Repository navigation
Using Jsonix in Node.js Programs
Alexey Valikov edited this page Sep 4, 2015
·
2 revisions
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.
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));