-
Notifications
You must be signed in to change notification settings - Fork 6
Introducing DynMap
danielhfrank edited this page Aug 30, 2011
·
4 revisions
DynMap (short for dynamic map) is an extension of a regular hashmap that does automatic type conversions and other goodness. It understands JSON natively, is exportable as JSON or XML and is selectable with the dot operator (i.e. get("key1.key2"). The features are best explained by example so here goes:
//create from json string
DynMap mp = DynMapFactory.instance("{ \\"key\\" : 90 }");
//select as integer
int asInt = mp.get(Integer.class, "key");
//select as a string
String str = mp.get(String.class, "key");
//select as Double
double asDouble = mp.get(Double.class, "key");
//a more complicated JSON string
DynMap mp = DynMapFactory.instance("{ \\"key\\" : 90," +
"\\"map1\\" : {" +
"\\"key2\" : \\"today\\"" +
"}," +
"\\"list\\" : [ 1,2,3]" +
" }");
//select by dot operator
//returns "today"
String str = mp.get(String.class, "map1.key1");
//typed lists
List<Integer> nums = mp.getList(Integer.class, "list");
//as Strings
List<Integer> numsAsStrings = mp.getList(String.class, "list");
Working with Dates is easy.
Dates are natively ISO
DynMap mp = new DynMap();
mp.put("date1","1997-07-16T19:20:30.45+01:00");
mp.put("date2",new DateTime()); //if you like using jodatime
mp.put("date3", new Date());
Date date1 = mp.get(Date.class, "date1");
Date date2 = mp.get(Date.class, "date2");
String isoDateString = mp.get(String.class, "date3");
More on lists
DynMap mp = new DynMap();
mp.put("list1", "0,1,2,3");
//will convert from string with the 'delimiter' param
mp.getList(Integer.class, "list1", ",");
mp.getList(String.class, "list1", ",");
Booleans
DynMap mp = new DynMap();
mp.put("bool1", "true");
mp.put("bool2", "f");
mp.put("bool3", "on");
mp.put("bool4", "yes");
mp.get(Boolean.class, "bool1"); //true
mp.get(Boolean.class, "bool2"); //false
mp.get(Boolean.class, "bool3"); //true
mp.get(Boolean.class, "bool4"); //true