JsonValidationError(List(error.expected.jsobject) while parsing object

I parsed object to Json in my writes method, but got an error JsonValidationError(List(error.expected.jsobject)

override def writes(o: UploadedFile): JsValue = JsObject(
  Seq("path" -> JsString(o.path.toString), "content" -> JsString(Json.stringify(Json.toJson(o.content))))
)

UploadedFile.fileContent - is an object to as UploadedFile and has its own implicit formatter,

final case class UploadedFileContent(content: String)

object UploadedFileContent {
  implicit val uploadedFileContentFormat: OFormat[UploadedFileContent] = Json.format[UploadedFileContent]
}

and UploadedFile formatter:

object UploadedFile {

  implicit object UploadedFileFormat extends Format[UploadedFile] {
    override def reads(json: JsValue): JsResult[UploadedFile] =
      JsSuccess(
        UploadedFile(Paths.get((json \ "path").as[String]), (json \ "content").as[UploadedFileContent])
      )

    override def writes(o: UploadedFile): JsValue = JsObject(
      Seq("path" -> JsString(o.path.toString), "content" -> JsString(Json.stringify(Json.toJson(o.content))))//error is smw here
    )
  }
}

Maybe I need something instead of Json.stringify(Json.toJson(o.content)) in my writes method, but I don't know what exactly. Tried a lot variants

Upvotes: 0

Views: 1811

Answers (2)

cchantep
cchantep

Reputation: 9168

If UploadedFile is a case class:

implicit val format: OFormat[UploadedFile] = Json.format

Upvotes: 1

  implicit lazy val UploadedFileFormat: OFormat[UploadedFile] = {
    ((JsPath \ "path").format[Path] ~ (JsPath \ "content")
      .format[UploadedFileContent])(UploadedFile.apply, unlift(UploadedFile.unapply))
  }

Upvotes: 0

Related Questions