Play Scala: json writer for nested classes

I am using Play! Scala 2.2, and I have a problem displaying class in Json :

I have two classes with one depending on the other, as follows:

 case class Artist(id: String, cover: String, website: List[String], link: String, Tracks: List[Track] = List()) case class Track(stream_url: String, title: String, artwork_url: Option[String] ) 

And their implicit writers:

 implicit val artistWrites: Writes[Artist] = Json.writes[Artist] implicit val trackWrites: Writes[Track] = Json.writes[Track] 

Authors work well, as shown below:

 println(Json.toJson(Track("aaa", "aaa", Some("aaa")))) println(Json.toJson(Artist("aaa", "aaa", List("aaa"), "aaa", List()))) 

ie, if Artist has an empty list of tracks . But if I want to do this:

 println(Json.toJson(Artist("aaa", "aaa", List("aaa"), "aaa", List(SoundCloudTrack("ljkjk", "ljklkj", Some("lkjljk")))))) 

I get a execution exception : [NullPointerException: null]

Could you explain to me what I am doing wrong? Thanks;)

+5
source share
1 answer

The problem is the initialization order. Json.writes[Artist] requires an implicit Writes[Track] to generate itself. The compiler can find the implicit Writes[Track] because you declare it in the same object, however trackWrites initialized after artistWrites , which means that when Json.writes[Artist] trackWrites is trackWrites there is null . However, this does not interrupt the creation of artistWrites , so it goes unnoticed until it is used.

You can fix this by simply switching the initialization order so that trackWrites first.

+4
source

Source: https://habr.com/ru/post/1213771/


All Articles