Alpakka JSON Reading

The way you currently have it written is that the Source returns a [Future[Future[Terminated]. Therefore, the program ends before your future(s) return.

There’s also a problem with the select, so I just changed it to root ($), and increased the buffer so that it looks like this:

...
  val done: Future[Done] = Source.single(ByteString.fromString(data))
    .via(JsonReader.select("$"))
    .via(JsonFraming.objectScanner(1000))
    .map(_.utf8String)
    .runForeach(x => println(s"element: $x"))

  done
    .map { _ =>
      println("Finished !")
      actorSystem.terminate()
    }
    .recover {
      case e: Exception => println(s"Failed ! ${e.getMessage}")
        actorSystem.terminate()
    }

My output looks like this:

2022-06-22 13:58:27,507 INFO  akka.event.slf4j.Slf4jLogger [] - Slf4jLogger started
element: {"id":1,"name":"Bulbasaur","type":["Grass","Poison"],"HP":45,"Attack":49,"Defense":49,"Sp. Attack":65,"Sp. Defense":65,"Speed":45}
element: {"id":2,"name":"Ivysaur","type":["Grass","Poison"],"HP":60,"Attack":62,"Defense":63,"Sp. Attack":80,"Sp. Defense":80,"Speed":60}
Finished !
2022-06-22 13:58:27,865 INFO  akka.actor.CoordinatedShutdown [custom-system-akka.actor.default-dispatcher-5] - Running CoordinatedShutdown with reason [ActorSystemTerminateReason]

I’ll leave it to you to tune your select.

Best, Michael

1 Like