toJson(地图(“成功” - > true,“消息” - > str))无法在play2中编译

时间:2012-03-28 14:22:19

标签: json playframework-2.0

这是我的代码:

import play.api.mvc._
import play.api.libs.json._
import play.api.libs.json.Json._
import play.api.libs.json.Writes._

class BaseController extends Controller with Secured with DefaultWrites {

  private implicit def str2json(str: String) = new {
    def asSuccessJson = toJson(Map("success" -> true, "message" -> str)) // (*)
    def asFailedJson = toJson(Map("success" -> false, "message" -> str)) // (*)
  }

}

但它不能在两个(*)行上编译。错误消息是:

Multiple markers at this line
- No Json deserializer found for type scala.collection.immutable.Map[java.lang.String,Any]. Try 
 to implement an implicit Writes or Format for this type.
- not enough arguments for method toJson: (implicit tjs: 
     play.api.libs.json.Writes[scala.collection.immutable.Map[java.lang.String,Any]])
     play.api.libs.json.JsValue.Unspecified value parameter tjs.

我必须把它写成:

def asSuccessJson = toJson(Map("success" -> true.toString, "message" -> str))

注意true.toString。它很有效但很无聊。

如何解决?

1 个答案:

答案 0 :(得分:6)

这很合乎逻辑:您尝试将异构映射转换为JsValue:

Map("success" -> true, "message" -> str)Map[String, Any]

没有隐式作者能够将Map[String, Any]转换为JsValue(并且不能有任何)。

当您编写Map("success" -> true.toString, "message" -> str)时,您创建了一个Map [String,String],并且有一个编写器。

我会写:

def asSuccessJson = JsObject(Seq("success" -> JsBoolean(true), "message" -> JsString(str))) // (*)
顺便说一句,JSON API肯定会在Play 2的下一个版本中被“美化”......