Why do you need to create these json for read / write when you do not need in java?

Please correct me if I am wrong, but when using Java with Spring MVC you did not need to create these additional classes to map your Java class to JSON and JSON for the class.

Why should you do this on Play with Scala? Does it have anything to do with Scala?

case class Location(lat: Double, long: Double)

implicit val locationWrites: Writes[Location] = (
  (JsPath \ "lat").write[Double] and
  (JsPath \ "long").write[Double]
)(unlift(Location.unapply))


implicit val locationReads: Reads[Location] = (
  (JsPath \ "lat").read[Double] and
  (JsPath \ "long").read[Double]
)(Location.apply _)
+4
source share
4 answers

The reason you should do it on Play is the framework design , and it is very good.

Play Scala implicits, , , , :

Json.toJson(Location(4.5, 5.3)) 

, . Scala , , " " . Reads/Writes .

object MyImplicits {

    object ImplicitJson1{
        implicit val write:Write[Location] = "write to json all fields"
    }

    object ImplicitJson2{
        implicit val write:Write[Location] = "skip field a"
    }
}

object MyBusinessCode{

    def f1(location:Location){
        import MyImplicits.ImplicitJson1._
        Json.toJson(location)
    }
    def f2(location:Location){
        import MyImplicits.ImplicitJson2._
        Json.toJson(location)
    }

    def dynamicChoice(location:Location){
        implicit val write = {
            if(location.isEurope)           
                MyImplicits.ImplicitJson1.write
            else
                MyImplicits.ImplicitJson2.write
        }
        Json.toJson(location)
    }

}

Spring . , , Spring , Json . , , .

, Scala/framework .

implicit val fmt = Json.format[Location]

- , , Play json .

+11

:

case class Location(lat: Double, long: Double)

object Location {

  implicit val fmt = Json.format[Location]

}

Json.toJson(Location(4.5, 5.3)) // returns JsValue

//, JSON .

+1

, JSON/ Spring , JSON Jackson/Spring. , Java Beans. .

Play Scala Json JSON. map, flatMap, orElse .. .

. :

https://softwareengineering.stackexchange.com/questions/228193/json-library-jackson-or-play-framework

+1

,

def toJson[T](x: T)(implicit fmt: Reads[T] = Json.format[T]) = Json.toJson(x)(fmt)

Play Json , Json.format [T] - , T. , (. sources)

, , , , Apply (Json.format [T]) AST JsMacroImpl.macroImpl (c, "format",...).

, - .

0

All Articles