Thursday, March 4, 2010

java to json using a javascript constructor -- classy javascript

i've got a simple class with both java and javascript representations

// java
package foobar;
public static class FoodStuff {
  String name;
  int index;

// javascript
foobar = {}
foobar.FoodStuff = function() {}
foobar.FoodStuff.prototype.blah = function() { return 7*this.index + name; }
foobar.mix = function(obj,props) { for (var ii in props) obj[ii] = props[ii]; return obj; }

i want to convert an java instance to json, and then instantiate it in javascript using the javascript class as the constructor. normally the json might look like '{name:"Sarah",index:77}'. i'd like to be able to do something like this

'{ food: foobar.mix( new foobar.FoodStuff(), { name:"Sarah", index:77 } ) }'

then i could (in javascript, where data has been assigned the string above, eg by an xhr call) say

var stuff = foobar.fromJson( data );
var magicValue =;

for this simple example i could obviously just augment in javascript, but for a bigger heirarchy of data, i don't want to have to decend and replace the whole thing with a bunch of different constructors. i think that gson is going to support this in the next version by allowing custom serializers to call the default serializer, which should allow me to wrap the obj with my foobar.mix

is there an easy way to accomplish this in jackson or gson ? or another json serializer that does automatic conversion of POJOs (ie without getters and setters) to json ?

note: i don't want to serialize the data myself, i just want to augment it. ideally i'd just set an annotation that told jackson what javascript constructor should be used, but wrapping the default serialization myself would be fine if it was easy enough

No comments: