Skip to content

Instantly share code, notes, and snippets.

@nornagon
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nornagon/10665331 to your computer and use it in GitHub Desktop.
Save nornagon/10665331 to your computer and use it in GitHub Desktop.
Serializer for squants.Quantity
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