Created
June 20, 2012 22:15
-
-
Save dornatsky/2962555 to your computer and use it in GitHub Desktop.
(almost) transparent maps serialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.novus.salat._ | |
import com.novus.salat.global._ | |
import com.mongodb.casbah.Imports._ | |
import com.novus.salat.annotations._ | |
case class KeyValuePair[K, V](key: K, value: V) | |
object DaoMap { | |
implicit def toDaoMap[K, V](map: Map[K, V]): Seq[KeyValuePair[K, V]] = { | |
//TODO handle nested maps | |
map.toSeq.map(x => { | |
val v = x._2 match { | |
case m: Map[_, _] => toDaoMap(m) | |
case other => other | |
} | |
new KeyValuePair(x._1, v.asInstanceOf[V]) | |
}).toSeq | |
} | |
//Because of type erasure reverse conversion becomes hard if not impossible. | |
//Generic KeyValuePair is converted to List[Any] containing values of its two fields. | |
} | |
object Main extends scala.App { | |
print("========\n") | |
import DaoMap._ | |
val test = Test("someId", Map("a.b" -> "c")) | |
val serialized = grater[Test].asDBObject(test).toString | |
val deserialized = grater[Test].fromJSON(serialized) | |
val originalMap = deserialized._map | |
print(serialized.toString + "\n") | |
print(deserialized.toString + "\n") | |
print(originalMap.toString() + "\n") | |
print("\n========\n") | |
} | |
trait MapRestore { | |
def restoreMap(seq: Seq[Any]): Map[Any, Any] = { | |
seq.map(x => { | |
val list = x.asInstanceOf[Seq[Any]] | |
//TODO handle nested maps, | |
//Is there a way to recognize a nested map? | |
// Map(a-> Map(b->c, d->e)) | |
// will be turned into [[a, [[b,c],[d,e]]]] | |
//I guess any array of arrays of length 2 can be treated as a map. | |
(list(0), list(1)) | |
}).toMap | |
} | |
} | |
case class Test( | |
id: String, | |
map: Seq[KeyValuePair[String, String]]) extends MapRestore { | |
lazy val _map = restoreMap(map) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment