Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Json: custom reads one field

Let's say I have to write custom Reads[Person] for Person class:

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

implicit val personReads: Reads[Person] = (
    (__ \ "name").read[String] and // or ~
    (__ \ "age").readNullable[Int]
) ((name, age) => Person(name = name, age = age))

it works like a charm, really (no).

But what can I do when there is only one field in json object?

The core of Reads and Writes is in functional syntax which transforms these "parse" steps.

The following does not compile:

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

implicit val personReads: Reads[Person] = (
  (__ \ "name").read[String]
)(name => Person(name))

Could you advice how to deal with it?

like image 407
Andrii Abramov Avatar asked Sep 21 '17 15:09

Andrii Abramov


1 Answers

Option 1: Reads.map

import play.api.libs.json._

case class Person(name: String)

object PlayJson extends App {
  implicit val readsPeson: Reads[Person] =
    (__ \ "name").read[String].map(name => Person(name))

  val rawString = """{"name": "John"}"""
  val json = Json.parse(rawString)
  val person = json.as[Person]
  println(person)
}

Option 2: Json.reads

import play.api.libs.json._

case class Person(name: String)

object Person {
  implicit val readsPerson = Json.reads[Person]
}

object PlayJson extends App { 
  val rawString = """{"name": "John"}"""
  val json = Json.parse(rawString)
  val person = json.as[Person]
  println(person)
}
like image 103
Mario Galic Avatar answered Oct 10 '22 17:10

Mario Galic