2

Trying to convert class to Json. Here is my class, it includes other two classes:

case class GoodEdit(good: Good, data: List[(String, Option[GoodText])])
case class Good(
  id: Long,
  partnumber: Option[String] = None
)
case class GoodText(
  goodid: Long,
  languageid: Long,
  title: String,
  description: Option[String] = None)

And here are my writers:

object GoodWriters {
  implicit val goodWrites = new Writes[Good] {
    def writes(good: Good) = Json.obj(
      "id" -> good.id,
      "partnumber" -> good.partnumber
    )
  }

  implicit val goodTextWrites = new Writes[GoodText] {
    def writes(goodText: GoodText) = Json.obj(
      "goodid" -> goodText.goodid,
      "languageid" -> goodText.languageid,
      "title" -> goodText.title,
      "description" -> goodText.description
    )
  }

  implicit val GoodEditWrites = new Writes[GoodEdit] {
    def writes(goodEdit: GoodEdit) = Json.obj(
      "good" -> Json.toJson(goodEdit.good),
      "data" -> Json.toJson(
        for ((lang, goodTextOpt) <- goodEdit.data ) yield Json.obj(lang -> goodTextOpt)
      )
    )
  }

Then, in controller I try it to use like this:

  Action {
    import jwriters.GoodWriters._
    GoodEditAggregate.get(id).map{
      a => Ok(Json.toJson(a))
    }.getOrElse(Ok(Json.toJson(Json.obj("status" -> "error","message" -> "Can't find good with this id"))))
  }

And compilator complaining on this part: Ok(Json.toJson(a))

No Json serializer found for type GoodEdit. Try to implement an implicit Writes or Format for this type

Can't understand what is wrong. I've imported writers for objects already

2
  • 1
    Do you have another Writes implementations imported\defined in the same context? It could be ambiguous implicits Commented Oct 24, 2015 at 11:46
  • Thanks, seems you were right Commented Oct 24, 2015 at 19:14

1 Answer 1

0

Try to Import Goodwrites globally

Sign up to request clarification or add additional context in comments.

3 Comments

Can you show how correctly write goodEdit.data.toMap? goodwriters object is in another file already.
"data" -> Json.toJson(goodEdit.data.toMap) where you had for expression. Your code have no errors, It runs correctly on my play app 2.4, I think the problem is in imports, try to import GoodWriters globaly
Thanks. I've imported GoodWriters globaly and now everything fine. Please make it as answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.