Providing JSON with Play! and scala

I have a simple question regarding the rendering of a JSON object from a Scala class. Why should I execute a deserializer (read, write).

I have the following case class:

case class User(firstname:String, lastname:String, age:Int) 

And in my controller:

 val milo:User = new User("Sam","Fisher",23); Json.toJson(milo); 

I get a compilation error: No Json handle for model types. Try to implement implicit Writes or Format for this type.

In my previous project, I had to implement the reader, the author object in the class, so that it worked, and I find it very annoying.

 object UserWebsite { implicit object UserWebsiteReads extends Format[UserWebsite] { def reads(json: JsValue) = UserWebsite( (json \ "email").as[String], (json \ "url").as[String], (json \ "imageurl").as[String]) def writes(ts: UserWebsite) = JsObject(Seq( "email" -> JsString(ts.email), "url" -> JsString(ts.url), "imageurl" -> JsString(ts.imageurl))) } } 
+6
source share
5 answers

I really recommend updating to play 2.1-RC1, because here the JSON authors / readers are very easy to define (more info here )

But to help you avoid some mistakes, I will give you a hint with the import: - use only this import! (note that json.Reads is not included)

 import play.api.libs.json._ import play.api.libs.functional.syntax._ import play.api.libs.json.Writes._ 

and you only need to write this code to write / read your class to / from Json (of course, you will have User instead of Address :

 implicit val addressWrites = Json.writes[Address] implicit val addressReads = Json.reads[Address] 

Now they will be used automatically:

Write example:

 Ok(Json.toJson(entities.map(s => Json.toJson(s)))) 

Read example (I put my POST execution example to create an object by reading json from the body), please pay attention to addressReads here

 def create = Action(parse.json) { request => request.body.validate(addressReads).map { entity => Addresses.insert(entity) Ok(RestResponses.toJson(RestResponse(OK, "Succesfully created a new entity."))) }.recover { Result => BadRequest(RestResponses.toJson(RestResponse(BAD_REQUEST, "Unable to transform JSON body to entity."))) } } 

In conclusion, they tried (and succeeded) to make things very simple with respect to JSON.

+9
source

If you use play 2.0.x, you can do

 import com.codahale.jerkson.Json._ generate(milo) 

generate uses reflection to do this.

In game 2.1, you can use Json.writes to create a macro for this implicit object that you had to create. No reflection required during operation!

 import play.api.libs.json._ import play.api.libs.functional.syntax._ implicit val userWrites = Json.writes[User] Json.toJson(milo) 
+3
source

I use jerkson (which is basically a wrapper for jackson) in my project to convert objects to json string.

The easiest way to do this:

 import com.codehale.jerkson.Json._ ... generate(milo) ... 

If you need to configure ObjectMapper (for example, add a custom serializer / deserializer, configure the output format, etc.), you can do this by creating an object that extends the class com.codehale.jerkson.Json .

 package utils import org.codehaus.jackson.map._ import org.codehaus.jackson.{Version, JsonGenerator, JsonParser} import com.codahale.jerkson.Json import org.codehaus.jackson.map.module.SimpleModule import org.codehaus.jackson.map.annotate.JsonSerialize object CustomJson extends Json { val module = new SimpleModule("CustomSerializer", Version.unknownVersion()) // --- (SERIALIZERS) --- // Example: // module.addSerializer(classOf[Enumeration#Value], EnumerationSerializer) // --- (DESERIALIZERS) --- // Example: // module.addDeserializer(classOf[MyEnumType], new EnumerationDeserializer[MyEnumType](MyEnumTypes)) mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL) mapper.setSerializationConfig(mapper.getSerializationConfig.without(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES)) mapper.registerModule(module) } 

To use it in your codes:

 import utils.CustomJson._ ... generate(milo) ... 
0
source

Actually it is very simple. First, import:

 import play.api.libs.json._ 

Because User is a case class, you can automatically create Json entries using Json.writes []:

 val milo:User = new User("Millad","Dagdoni",23) implicit val userImplicitWrites = Json.writes[User] Json.toJson(milo) 

I did not find it in the docs, but here is the api link: http://www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.libs.json.Json $

0
source

In your case, I would use the JSON.format macro.

 import play.api.libs.json._ implicit val userFormat = Json.format[User] val milo = new User("Sam", "Fisher", 23) val json = Json.toJson(milo) 
0
source

All Articles