Giter VIP home page Giter VIP logo

play-framework-reference's People

Contributors

nummy avatar

Stargazers

 avatar

Watchers

 avatar  avatar

play-framework-reference's Issues

JSON自动映射

如果JSON能够直接映射到对应的类,那么可以省去写Reads[T]、Writes[T]或Format[T]的麻烦。

假设存在样式类Resident:

case class Resident(name: String, age: Int, role: Option[String])

下面的代码创建一个Reads[Resident]:

import play.api.libs.json._

implicit val residentReads = Json.reads[Resident]

当程序编译的时候,Play会自动检查我们的类,然后插入以下代码:

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

implicit val residentReads = (
  (__ \ "name").read[String] and
  (__ \ "age").read[Int] and
  (__ \ "role").readNullable[String]
)(Resident)

同样的,我们还可以创建:

import play.api.libs.json._

implicit val residentWrites = Json.writes[Resident]
import play.api.libs.json._

implicit val residentFormat = Json.format[Resident]

但是这样做的话,我们定义的类必须满足以下条件:

  • 必须拥有伴生对象,伴生对象还必须有apply和unapply方法;
  • unapply返回的结果类型必须与apply参数的类型一致;
  • apply参数的名字必须和JSON的参数名一致;

样式类刚好满足上述要求,所以原生支持。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.