Wednesday, October 27, 2010

Jsonix - JAXB for JavaScript

Folowing up on the ideas from my previous posts, I've started the project called Jsonix (JSON interfaces for XML):

http://confluence.highsource.org/display/MISC/Jsonix

Jsonix is basically a JAXB analog for JavaScript. With Jsonix you can:
  • parse XML into JSON;
  • serialize JSON into XML;
  • define XML/JSON mappings declaratively;
  • generate Jsonix mappings from XML Schemas.

Here's a small example of how a JSON purchase order could be marshalled in XML:

var context = Jsonix.Context.newInstance([ PO ]);
// Marshal JSON as XML (DOM node)
var unmarshaller = context.createUnmarshaller();

var node = marshaller.marshal({
name: {localPart: "purchaseOrder"},
value: {
shipTo: {
name: "Alice Smith",
street: "123 Maple Street",
city: "Mill Valley",
state: "CA",
zip: 90952
}
}
});


This will produce an XML like:
<purchaseOrder orderDate="1999-10-20">
<shipTo country="US">
<name>Alice Smith</name>
<street>123 Maple Street</street>
<city>Mill Valley</city>
<state>CA</state>
<zip>90952</zip>
</shipTo>
<!-- ... -->
</purchaseOrder>


And here's how you'd unmarshal:

// Unmarshal JSON from XML (retrieved from an URL)
var unmarshaller = context.createUnmarshaller();
unmarshaller.unmarshal({
url : "po.xml",
success : function(po) {
assertEquals("purchaseOrder", po.name.localPart);
assertEquals("Alice Smith", po.value.shipTo.name);
}
});


The project is in development, I'll be working on it next weeks.

0 Comments:

Post a Comment

<< Home