Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

scala - How to turn json to case class when case class has only one field

In play 2.1 reads are used to marshall Json to objects. But how can I do this when the case class has only one field. The ideom that works for more fields does not work, as with one field 'and' is not used. Thus I do not get a FunctionBuilder.

The following code gives me a type mismatch. How can I fix this?

case class Data(stamm: Seq[String])


implicit val dataReads  = (
  (__  "stamm").read(Reads.list[String])
)(Data)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Julien answered, you can read single field case classes using this:

case class Person(name: String)

val personReads: Reads[Person] = 
  (__  "name").read[String].map { name => Person(name) }

Just a complement, if you want to write:

val personWrites: Writes[Person] = 
  (__  "name").write[String].contramap { (person: Person) => person.name }

Or format (read and write):

val personFormat: Format[Person] = 
  (__  "name").format[String].inmap(name => Person(name), (person: Person) => person.name)

For write and format you have to import this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...