Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 11th, 2012  |  syntax: None  |  size: 1.98 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How can I map List<MyObject> to List<HashMap<String,Object>> with Dozer?
  2. public class Foo{
  3.     String fooStr;
  4.     List<Bar> barList;
  5.  
  6.     //get/set barList/someStr go here
  7. }
  8.  
  9. public class Bar {
  10.     String barStr;
  11. }
  12.        
  13. <mapping>
  14.     <class-a>Foo</class-a>
  15.     <class-b>java.util.Map</class-b>
  16.  
  17.     <field>
  18.         <a>bar</a>
  19.         <b key="bar">this</b>
  20.         <a-hint>Bar</a-hint>
  21.         <b-hint>java.util.Map</b-hint>
  22.     </field>
  23. </mapping>
  24.        
  25. {
  26.     "fooStr" : "value of fooStr",
  27.     {
  28.        "barStr" : "value of barStr"
  29.     }
  30. }
  31.        
  32. {
  33.     "fooStr" : "value of fooStr",
  34.     "barList" : [{ "barStr" : "bar1" }, { "barStr" : "bar2" }, ...]
  35. }
  36.        
  37. public class Foo {
  38.     String fooStr;
  39.     List<Bar> barList;
  40.     ...
  41. }
  42.  
  43. public class Bar {
  44.     String barStr;
  45. }
  46.  
  47. public class Target {
  48.     String fooStr;
  49.     Map<String, Bar> barMap;  
  50. }
  51.  
  52.  
  53. public class TestCustomConverter implements CustomConverter {
  54.  
  55.   public Object convert(Object destination, Object source, Class destClass, Class sourceClass) {
  56.     if (source == null) {
  57.       return null;
  58.     }
  59.     if (source instanceof Foo) {
  60.       Map<Bar> dest = null;
  61.       // check to see if the object already exists
  62.       if (destination == null) {
  63.         dest = new Target();
  64.       } else {
  65.         dest = (Target) destination;
  66.       }
  67.       ((Target) dest).setFooStr(source.getFooStr());
  68.       for(Bar : source.getBarList()) {
  69.           ((Target) dest).getBarMap().put(bar.getBarStr(), bar);
  70.       }
  71.       return dest;
  72.     } else if (source instanceof Target) {
  73.       Foo dest = null;
  74.       // check to see if the object already exists
  75.       if (destination == null) {
  76.         dest = new Foo ();
  77.       } else {
  78.         dest = (Foo) destination;
  79.       }
  80.       dest.getFoos().addAll(((Target)source).getBarMap().values());
  81.       dest.setFooStr(((Target)source).getFooStr()):
  82.       return dest;
  83.     } else {
  84.       throw new MappingException("Converter TestCustomConverter used incorrectly. Arguments passed in were:"
  85.           + destination + " and " + source);
  86.     }
  87.   }