1

我正在做一个小项目,尝试让 Scala/Play 后端正常工作。我试图让它返回并在 Web 服务端处理 JSON。我似乎无法弄清楚如何让 JSON 编组和解组工作。有人可以帮我解决这个问题吗?我正在使用 Play 2.1 和 Scala 2.10。我得到的错误是“重写方法读取类型的特征读取(json:play.api.libs.json.JsValue)play.api.libs.json.JsResult [models.Address];方法读取具有不兼容的类型”

  • 已编辑。其他人给了我解决方案。对于阅读,您必须使用 JsSuccess,而不是 JsResult。

    case class Address(id: Long, name: String)
    
    object Address {
    
    implicit object AddressFormat extends Format[Address] {
    def reads(json: JsValue):Address = JsSuccess(Address(
        (json \ "id").as[Long],
        (json \ "name").as[String]
    ))
    
    def writes(address: Address): JsValue = JsObject(Seq(
        "id" -> JsNumber(address.id),
        "name" -> JsString(address.name)
    ))
    }
    }
    
4

3 回答 3

3

使用 Play 2.1,您可以简化代码:

import play.api.libs.json._
import play.api.libs.functional.syntax._

implicit val addressFormat = (
  (__ \ "id").format[String] and
  (__ \ "name").format[Long]
)(Address.apply, unlift(Address.unapply))

更详细的信息可以在这里找到:ScalaJsonCombinators

于 2013-02-16T11:29:34.643 回答
2

您可以使用宏进一步简化代码,尽管它们被标记为实验性的:

import play.api.libs.json._
import play.api.libs.functional.syntax._

case class Address(id: Long, name: String)

implicit val addressFormat = Json.format[Address]

Play 官方文档中有关此技术的更多详细信息。

于 2013-02-16T20:54:33.877 回答
0

Hey my solution would be:

import play.api.libs.json.JsonNaming.SnakeCase
import play.api.libs.json._

object Test {

  implicit val config = JsonConfiguration(SnakeCase)
  implicit val userFormat: OFormat[Test] = Json.format[Test]

}

case class Test(
                 testName: String,
                 testWert: String,
                 testHaus: String
               )

In conclusion, you get a compenion object. The config converts all keys of the case class into snakecase. The implicit values ensure that a valid Json can be parsed into a model. So you get your test model back.

The Json should look like this:

{
    "test_name" : "Hello",
    "test_wert": "Hello",
    "test_haus": "Hello"
}

https://www.playframework.com/documentation/2.6.x/ScalaJsonAutomated

于 2018-01-12T21:30:36.687 回答