You should change the code in your controller to:
val req = (json \ "references").as[References]
سؤال
I have the following Json string:
{
"references": {
"configuratorId": "conf id",
"seekId": "seekid",
"hsId": "hsid",
"fpId": "fpid"
}
}
And i want to create an object from it in my Rest API Controller.
The code:
case class References(configuratorId: Option[String], seekId: Option[String], hsId: Option[String], fpId: Option[String]) {}
The Formatter:
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]]
))
}
Code in my controller:
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")
}
}
The object is full with null values.. I guess my reads is wrong - but i cant figure out why.
Thanks!!
المحلول
You should change the code in your controller to:
val req = (json \ "references").as[References]