0

案子

本案例使用 Scala、Play Framework、Jerkson 和 Squeryl。我正在尝试将查询结果集转换为 JSON,但结果仅显示“持久”字段。

问题

为什么 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
},
4

1 回答 1

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"
  }
]
于 2012-08-28T20:14:00.500 回答