2011年12月11日日曜日

play-scala using Gson for Scala class

before post,
http://tech-snippet.blogspot.com/2011/11/play-scala-using-gson.html
I wrote play-scala sample return in JSON format.
If you are serialized, that does not work with Scala class.

so,For example, if anorm's model has the Option or Pk ,Serialization is not good.
  case class User(
    id: Pk[Int],
    name:String
    email: Option[String])
  object User extends Magic[User]


Then I will use the Custom Serializer, to return any value.
  import com.google.gson._

    /**
     * for Pk[Int]
     */
    class PkSerializer extends JsonSerializer[Pk[Int]] {
      def serialize(src: Pk[Int], typeOfSrc: Type, context: JsonSerializationContext): JsonElement = {
        new JsonPrimitive(src.apply);
      }
    }

    /**
     * for Option
     */
    class OptionSerializer extends JsonSerializer[Option[Any]] {
      def serialize(src: Option[Any], typeOfSrc: Type, context: JsonSerializationContext): JsonElement = {
        new JsonPrimitive(src.getOrElse("none").toString());
      }
    }
Serializer to convert an Option and Pk.
Pk as it returns its value, Option value if it Some, if None "none" returns a String.


Then serialized using created Custom Serializer.
 import play._
 import play.mvc._
 import play.db.anorm._
 import com.google.gson._

  val builder = new GsonBuilder()
  builder.registerTypeAdapter(classOf[play.db.anorm.Pk[Int]], new PkSerializer)
  builder.registerTypeAdapter(classOf[Option[Any]], new OptionSerializer)
  val gson = builder.create()
  Json(gson.toJson())

Any type can be serialized in this way.

0 件のコメント:

コメントを投稿