Search code examples
scalasprayspray-json

Serialize Sequence[T] when I have a correct JsonFormatter for T


I'm trying to write a function that will dump a list of NbaPlayerBoxScore to a json file. I have written a JsonFormat function which is able to serialize NbaPlayerBoxScore to the file. However, I want to write a Seq[NbaPlayerBoxScore] to the file. Here is my attempt

def dumpToJsonFile(contents : Seq[NbaPlayerBoxScore], protocol : JsonFormat[NbaPlayerBoxScore]) : Unit = {
      import protocol._
      val w = new BufferedWriter(new FileWriter(fileName))
      w.write(contents.toJson.prettyPrint)
      w.close
    }

and here is the error I get:

[error] /home/chris/dev/nba-api/src/main/scala/io/extrapoint/nbaapi/models/NbaPlayerBoxScoreDAO.scala:174: Cannot find JsonWriter or JsonFormat type class for Seq[io.extrapoint.nbaapi.models.NbaPlayerBoxScore]
[error]       w.write(contents.toJson.prettyPrint)
[error]                        ^
[error] one error found

How can I serialize a sequence of NbaPlayerBoxScore when I have a correct formatter for a single NbaPlayerBoxScore


Solution

  • I ended up solving my issue right after I posted this question. I used a implicit parameter for the formatter and then imported DefaultJsonProtocol

    Here is the solution:

    def dumpToJsonFile(contents : Seq[NbaPlayerBoxScore])(implicit protocol : JsonFormat[NbaPlayerBoxScore]) : Unit = {
      import DefaultJsonProtocol._
      val w = new BufferedWriter(new FileWriter(fileName))
      w.write(contents.toJson.prettyPrint)
      w.close
    }