1
我有以下的JSON字符串:轉換JSON來斯卡拉對象
{
"references": {
"configuratorId": "conf id",
"seekId": "seekid",
"hsId": "hsid",
"fpId": "fpid"
}
}
,我想在我的REST API控制器來創建一個對象。
代碼:
case class References(configuratorId: Option[String], seekId: Option[String], hsId: Option[String], fpId: Option[String]) {}
的格式化程序:
trait ProductFormats extends ErrorFormats {
implicit val referencesFormat = Json.format[References]
implicit val referenceFormat = new Format[References]{
def writes(item: References):JsValue = {
Json.obj(
"configuratorId" -> item.configuratorId,
"seekId" -> item.seekId,
"hsId" -> item.hsId,
"fpId" -> item.fpId
)
}
def reads(json: JsValue): JsResult[References] =
JsSuccess(new References(
(json \ "configuratorId").as[Option[String]],
(json \ "seekId").as[Option[String]],
(json \ "hsId").as[Option[String]],
(json \ "fpId").as[Option[String]]
))
}
代碼在我的控制器:
def addProducts(lang: String, t: String) = Action {
request =>
request.body.asJson.map {
json =>
val req = json.as[References]
println(req.configuratorId.getOrElse("it was empty !!"))
Ok(Json.toJson((req)))
}.getOrElse {
println("Bad json:" + request.body.asText.getOrElse("No data in body"))
BadRequest("Incorrect json data")
}
}
目的是完全空值。我想我是讀錯 - 但我無法弄清楚爲什麼。
謝謝!