Question

I'm using playframework 2.1.0 with Anorm to query a db. I want to serialize the result to json without going through any interim objects/case classes.

this is what the flow looks like: Using anorm:

DB.withConnection { implicit c =>
  val q = SQL(""" long query goes here """)
  q().toList
}

then I take this result and transform it from a List[SqlRow] to List[Map[String,Any]]. String,Any is the column name, value (Object/Any)

val asMap = info.toList.map(row => scala.collection.immutable.Map(row.asMap.toSeq:_*))

The i'd like to jsonize this.

I tried some json libs : GSON, spray-json, playframework json lib. But none of them seem to work with Any out of the box. I tried writing implicit writer for the Any type with some pattern matching, but the problem is that this writer always overtakes all the other writes so the json is not produced correctly.

Advise? How would you suggest transforming a result from Anorm to Json? without any interim domain models.

Was it helpful?

Solution

found a solution, not the best, using FlexJson.
The annoying thing is that FlexJson is not very scala oriented so scala collections and some scala types need to be converted to the equivalent Java type.

val info:List[SqlRow] = loadInfoFromDB using Anorm
//transform scala maps to java maps
val asMap: List[util.Map[String, Any]] = info.toList.map(row => JavaConversions.mapAsJavaMap(row.asMap))
//create the basic FlexJson serializer
val flexJson: JSONSerializer = new flexjson.JSONSerializer()
//register a Option transformer so it can serialize Options correctly
flexJson.transform(new flexjson.transformer.AbstractTransformer {
  def transform(`object`: Any) {
    `object`.asInstanceOf[Option[_]] match {
      case None => getContext.write("null")
      case Some(b:Any) => getContext.transform(b)
    }
  }
},classOf[Option[_]])
//finally convert the scala List to java List and use this serializer on it.
val infoJsn: String = flexJson.deepSerialize(JavaConversions.seqAsJavaList(asMap))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top