Created
January 20, 2015 16:44
-
-
Save raelg/e12d731ba01ba58f0006 to your computer and use it in GitHub Desktop.
Scala Gson Serializer
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
package services | |
import java.lang.reflect.Type | |
import com.google.gson._ | |
import org.joda.time.format.ISODateTimeFormat | |
import org.joda.time.{DateTime, DateTimeZone} | |
object Serializers { | |
val DATE_TIME_FORMATTER = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC) | |
lazy val gson = new GsonBuilder() | |
.registerTypeHierarchyAdapter(classOf[Seq[Any]], new ListSerializer) | |
.registerTypeHierarchyAdapter(classOf[Map[Any,Any]], new MapSerializer) | |
.registerTypeHierarchyAdapter(classOf[Option[Any]], new OptionSerializer) | |
.registerTypeAdapter(classOf[DateTime], new DateTimeSerializer) | |
.create() | |
class ListSerializer extends JsonSerializer[Seq[Any]] { | |
override def serialize(src: Seq[Any], typeOfSrc: Type, context: JsonSerializationContext): JsonElement = { | |
import scala.collection.JavaConverters._ | |
context.serialize(src.toList.asJava) | |
} | |
} | |
class MapSerializer extends JsonSerializer[Map[Any,Any]] { | |
override def serialize(src: Map[Any,Any], typeOfSrc: Type, context: JsonSerializationContext): JsonElement = { | |
import scala.collection.JavaConverters._ | |
context.serialize(src.asJava) | |
} | |
} | |
class OptionSerializer extends JsonSerializer[Option[Any]] { | |
override def serialize(src: Option[Any], typeOfSrc: Type, context: JsonSerializationContext): JsonElement = { | |
src match { | |
case None => JsonNull.INSTANCE | |
case Some(v) => context.serialize(v) | |
} | |
} | |
} | |
class DateTimeSerializer extends JsonSerializer[DateTime] { | |
override def serialize(src: DateTime, typeOfSrc: Type, context: JsonSerializationContext): JsonElement = { | |
new JsonPrimitive(DATE_TIME_FORMATTER.print(src)) | |
} | |
} | |
} |
This is awesome, thanks a lot!
Thanks for that!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Neat way to handle Gson serializations in scala. Saved me a lot of time. Thanks.