Skip to content

Using Jsonix in Node.js Programs

John Carlson 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));

If you get an error like

/Users/johncarlson/Source/x3djson/mappings/x3djson.jsonschema:3
    "id":"#",
        ^
SyntaxError: Unexpected token :
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:413:25)
    at Object.Module._extensions..js (module.js:448:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/johncarlson/Source/x3djson/js/generatex3djson.js:2:21)
    at Module._compile (module.js:430:26)
    at Object.Module._extensions..js (module.js:448:10)

You are probably including the JSON and not the JS schema mappings.

If you get an error like:

/Users/johncarlson/Source/x3djson/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:292
        throw "Protocol not supported.";
        ^
Protocol not supported.

It's likely you need to use unmarshallFile instead of unmarshallURL.

Clone this wiki locally