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.

2011年11月17日木曜日

play-scala using Gson

I find out how to return data in JSON format using the play-scala.
In the play-scala around the handle JSON can present a very bad,
such as lift-json, prefer to work well with other libraries.

so I try to experiment,googl-served to keep a record so the easiest Gson.


1.create play application

$ play new jsonsample --with scala


2.get Gson lib

use dependency management eatures in play.

conf/dependencies.yml
# Application dependencies

require:
    - play
    - play -> scala 0.9
    - com.google.code.gson -> gson 1.7.1

and then,execute deps command.

$ cd jsonsample
$ play deps
available Gson.


3.create Controller

To create a Controller that will be returned in the Json format data from the default index method.

import com.google.gson.Gson

def index = {
    val gson: Gson = new Gson()
    val array = new Array[String](3)
    array(0) = "apple"
    array(1) = "orange"
    array(2) = "banana"
    Json(gson.toJson(array))  
}
the array returned in JSON format.
["apple","orange","banana"]

Map case.
※conversion from Scala Map to java.util.Map

import com.google.gson.Gson
import scala.collection.JavaConversions._

 def index = {
    val gson: Gson = new Gson()
   var map = Map("key1"->"val1", "key2"->"val2")
   val jMap: java.util.Map[String, String] = map
   Json(gson.toJson(jMap))  
  }

result is
{"key1":"val1","key2":"val2"}


Object in List case.
package controllers

import com.google.gson.Gson
import java.util.List
import java.util.ArrayList
import scala.collection.JavaConversions._

object Application extends Controller {

  def index = {
    val gson: Gson = new Gson()

    val user1 = Person("syuta",30)
    val user2 = Person("taro",20)

    val s1 = Skill("Java","Program language")
    val s2 = Skill("Scala","Program language")
    val s3 = Skill("MySQL","Database")
      
    val list1 = new ArrayList[Skill]
    list1.add(s1)
    list1.add(s2)
    list1.add(s3)
    
    user1.skills = list1

    val list2 = new ArrayList[Skill]
    list2.add(s2)
    list2.add(s3)

    user2.skills = list2

    val str1 = gson.toJson(user1)
   println(str1)

   val str2 = gson.toJson(user2)
   println(str2)
   
   val resList:List[Person] = new ArrayList[Person]()
    resList.add(user1)
    resList.add(user2)


    Json(gson.toJson(resList))
  }

}

case class Person(var name: String,var age: Int) {
  var skills:List[Skill] = _
}

case class Skill(var name: String,var category:String)

result is
[{"name":"syuta","age":30,"skills":[{"name":"Java","category":"Program language"},{"name":"Scala","category":"Program language"},{"name":"MySQL","category":"Database"}]},{"name":"taro","age":20,"skills":[{"name":"Scala","category":"Program language"},{"name":"MySQL","category":"Database"}]}]
no problem case class.

2011年10月31日月曜日

introduction

This blog is The English version of this site.
about
  • Play framework
  • Clojure
  • node.js
  • Android
and other tech info.