Last active
August 29, 2015 13:59
-
-
Save nornagon/10665331 to your computer and use it in GitHub Desktop.
Serializer for squants.Quantity
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
object Serialization { | |
object UnitSerialization { | |
val unitForSymbol = Map( | |
"millisecond" -> Milliseconds, | |
"celsius" -> Celsius, | |
"kelvin" -> Kelvin, | |
"meter" -> Meters, | |
"nanometer" -> Nanometers, | |
"second" -> Seconds, | |
"minute" -> Minutes, | |
"hour" -> Hours | |
) | |
val symbolForUnit: Map[squants.UnitOfMeasure[_],String] = | |
unitForSymbol map { case (x,y) => (y,x) } toMap | |
} | |
class QuantitySerializer extends Serializer[squants.Quantity[_]] { | |
private val QuantityClass = classOf[squants.Quantity[_]] | |
import UnitSerialization.{unitForSymbol, symbolForUnit} | |
case class QVal(val unit: String, val value: Double) | |
def deserialize(implicit format: Formats) = { | |
case (TypeInfo(k, _), json) if QuantityClass.isAssignableFrom(k) => | |
val q = json.extract[QVal] | |
unitForSymbol(q.unit)(q.value) | |
} | |
def serialize(implicit format: Formats) = { | |
case q: squants.Quantity[_] => | |
JObject(List( | |
"unit" -> JString(symbolForUnit(q.valueUnit)), | |
"value" -> JDouble(q.value) | |
)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment