如何将Squeryl查询对象转换为JSON - Play Framework

时间:2012-08-28 01:32:48

标签: json scala playframework playframework-2.0 squeryl

案例

本案例使用的是Scala,Play Framework,Jerkson和Squeryl。我正在尝试将查询结果集转换为JSON,但结果只显示'persisted'字段。

问题

为什么Json.generate()不打印所有实体字段?

控制器

package controllers.api

import play.api.mvc._
import play.Logger
import play.api.data.Form
import play.api.data.Forms.{mapping, text, optional}
import com.codahale.jerkson.Json
import org.squeryl.PrimitiveTypeMode._
import models.{ApplicationDatabase, Category}


object Categories extends Controller { 

  def findAll = Action {
    val json = inTransaction {
      val list = from(ApplicationDatabase.categories)(categories =>
        select(categories)
        orderBy(categories.title)
      )      
      Logger.info(list.toString)
      Json.generate(list)
    }

    Ok(json).as(JSON)
  }

  def findById(id: Long) = Action {
    val category = inTransaction { 
      ApplicationDatabase.categories.lookup(id)
    }

    Ok(Json.generate(category)).as(JSON)
  }

}

类别实体

package models

import org.squeryl.PrimitiveTypeMode._    
import org.squeryl.annotations.Column


class Category(var uid: String, var title: String) extends FlashcardsDbObject {

}

基本实体

package models;

import java.sql.Timestamp    
import org.squeryl._
import org.squeryl.annotations.{Column}
import org.squeryl.PrimitiveTypeMode._

class FlashcardsDbObject extends KeyedEntity[Long] {

  val id: Long = 0

  @Column("created_at")
  var createdAt = new Timestamp(System.currentTimeMillis)


  @Column("updated_at")
  var updatedAt = new Timestamp(System.currentTimeMillis)

}

问题

结果

{
  persisted: true
},
{
  persisted: true
},

预期

{
  id: 1,
  uid: 'chemistry',
  title: 'Chemistry'
  persisted: true
},
{
  id: 2,
  uid: 'biology',
  title: 'Biology'
  persisted: true
},

1 个答案:

答案 0 :(得分:0)

可能这不是最好的解决方案,但是当我导入并声明 JsonProperty 进入为我工作的字段时:

package models

import org.squeryl.KeyedEntity
import org.squeryl.annotations._
import org.squeryl.PrimitiveTypeMode._
import org.codehaus.jackson.annotate.JsonProperty


case class Category(val id: Int = 0,
                    @JsonProperty("uid")
                    val uid: String,
                    @JsonProperty("title")
                    val title: String) extends KeyedEntity[Int] {

}

<强>结果

[
  {
    id: 3,
    uid: "biology",
    title: "Biology"
  },
  {
    id: 1,
    uid: "general-chemistry",
    title: "General Chemistry"
  },
  {
    id: 4,
    uid: "organic-chemistry",
    title: "Organic Chemistry"
  },
  {
    id: 2,
    uid: "physics",
    title: "Physics"
  }
]