玩! Scala:Json读者和其他类字段

时间:2015-02-26 07:55:35

标签: json scala playframework-2.2

我正在玩Play! Scala 2.2和我正在阅读json如下,它很有效:

case class YoutubeTrack(//artistId: String,
                          videoId: String,
                          title: String,
                          thumbnail: Option[String] )
val youtubeTrackReads: Reads[YoutubeTrack] = (
      (__ \ "id" \ "videoId").read[String] and
        (__ \ "snippet" \ "title").read[String] and
        (__ \ "snippet" \ "thumbnails" \ "default" \ "url").readNullable[String]
      )(YoutubeTrack)

现在我想在我的YoutubeTrack class(在类声明中注释的artistId)中添加一个字段。 该字段是我在其他地方定义的变量。

如何在读取json的同时将此字段添加到我的YoutubeTrack,即我想做类似的事情:

val youtubeTrackReads: Reads[YoutubeTrack] = (
      (__ \ "id" \ "videoId").read[String] and
        (__ \ "snippet" \ "title").read[String] and
        (__ \ "snippet" \ "thumbnails" \ "default" \ "url").readNullable[String]
      )((artistId, videoId, title, url) => YoutubeTrack(artistId, videoId, title, url))

2 个答案:

答案 0 :(得分:1)

给定功能

def toArtistId(
    videoId: String,
    title: String,
    thumbnail: Option[String]): String = ...
  1. 您甚至可以在不更换阅读器的情况下添加您的艺术家ID

    case class YoutubeTrack(
        videoId: String,
        title: String,
        thumbnail: Option[String]) {
        val artistId = toArtistId(videoId, title, thumbnail)
    }
    
  2. 或者像这样改变你的读者

    (
        (__ \ "id" \ "videoId").read[String] and 
        (__ \ "snippet" \ "title").read[String] and
        (__ \ "snippet" \ "thumbnails" \ "default" \ "url").readNullable[String]
    )((videoId, title, thumbnail) => 
         YoutubeTrack(toArtistId(videoId, title, thumbnail), videoId, title, thumbnail)
    )
    
  3. 或者甚至喜欢这个

    def artistReader(artistId: String): Reads[YoutubeTrack] = {
        (
            (__ \ "id" \ "videoId").read[String] and
            (__ \ "snippet" \ "title").read[String] and
            (__ \ "snippet" \ "thumbnails" \ "default" \ "url").readNullable[String]
        )((videoId, title, thumbnail) => 
            YoutubeTrack(artistId, videoId, title, thumbnail))
    }
    
    artistReader("A")
    

答案 1 :(得分:0)

case class YoutubeTrackTemp(
  videoId: String,
  title: String,
  thumbnail: Option[ String ]
)

val youtubeTrackReads: Reads[ YoutubeTrack ] = (
  ( __ \ "id" \ "videoId" ).read[ String ] and
    ( __ \ "snippet" \ "title" ).read[ String ] and
    ( __ \ "snippet" \ "thumbnails" \ "default" \ "url" ).readNullable[ String ]
  )( YoutubeTrackTemp )

case class YoutubeTrack(
  artistId: String,
  videoId: String,
  title: String,
  thumbnail: Option[ String ]
)

object YoutubeTrack {
  def apply( yt: YoutubeTrackTemp ): YoutubeTrack = {
    val artistId = getArtistIdSomehow()
    YoutubeTrack( artistId, yt.videoId, yt.title, yt.thumbnail )
  } 
}

val youtubeTrack = YoutubeTrack( myjson.as[ YoutubeTrackTemp ] )