Playframework play.api.libs.json.Json.format real use case

I want to convert my stuff:

case class Message (
     var text: String = "",
     var `type`: String = "error"
 )

case class ValidationFieldError(
     var fieldName:String, message:Message,
     var value:String = "",
     var suggestions:List[String] = List[String]()
)

to json object ...

import play.api.libs.json.{Json, JsValue}

.. Here I try to use Json.format

implicit val validationFieldErrorFormat = Json.format[Message]
implicit val validationFieldErrorFormat = Json.format[ValidationFieldError]

.. when I do Json.toJson(errors) I get json array back. That's good. By I want to get json object back. To get back json structure like this:

{ 
  "email": { 
        "message": {"type": "error", "text": "email duplication"}, 
         "value": "", 
         "suggestions": [ ] 
      },
  "username" : {... etc. } 
}

I've been trying experimenting with it but gave up for now. Using StringBuilder to get desired json.

Q: what would be the way to make such a structure / transformation.

Answers


You can do something like that:

Json.obj(
  "email" -> Json.obj(
    "message" -> Json.obj("type" -> "error", "text" -> "email duplication"), // or use Json.toJson(your object)(implicit format) with desired Format 
    "value" -> "",
    "suggestions" -> Seq()
  ),
  "username" -> Json.obj(...)
)

Need Your Help

send request to a servlet from JSP on loading the JSP without user input(like button)

jsp servlets

I want to send request to a servlet "MyServlet" from a JSP "MyJsp.jsp" ,

qTip2 hide if empty content

javascript jquery qtip2

I load the text for the tooltip from a custom tag, data-tooltip. I'd like the tooltip to be hidden if the data-tooltip is not present. Is this possible?