Thursday, March 11, 2010

Want to convert JSON to Grails domain class object

http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html#toBean(net.sf.json.JSONObject, java.lang.Class, java.util.Map)

Check out the method "toBean()". It says:

JSONObject.toBean():returns JSONObject

public static Object toBean(JSONObject jsonObject,
                            Class beanClass,
                            Map classMap)
Creates a bean from a JSONObject, with a specific target class. If beanClass is null, this method will return a graph of DynaBeans. Any attribute that is a JSONObject and matches a key in the classMap will be converted to that target class. The classMap has the following conventions:
  • Every key must be an String.
  • Every value must be a Class.
  • A key may be a regular expression.
My usage:
Map classMap = new HashMap();
classMap.put("thumbPic", Picture.class);
classMap.put("lowPic", Picture.class);
classMap.put("highPic", Picture.class);
classMap.put("category", Category.class);
classMap.put("family", Family.class);
classMap.put("description", Description.class);
classMap.put("warranties", Warranty.class);
classMap.put("gallery", Gallery.class);
classMap.put("mediaObjects", Multimedia.class);
classMap.put("attributes", Attribute.class);
// create domain object of type Category
                JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(["MM/dd/yyyy HH:m m:ss"] as String[])); // creating JSON object. JSONObject jsonObject = JSONObject.fromObject(mockData); // getting object Object object = (Object) JSONObject.toBean(jsonObject, beanClass,classMap);
Also check Grails Converters Reference http://grails.org/Converters+Reference

1 comment:

  1. http://grails.org/doc/latest/api/org/codehaus/groovy/grails/web/json/JSONObject.html

    Is this a brand new function in grails?? I don't see the toBean function in the latest docs...

    ReplyDelete