Could not find implicit value of org.json4s.AsJsonInput in json4s 4.0.4

429 Views Asked by At

json4s version

In sbt: "org.json4s" %% "json4s-jackson" % "4.0.4"

scala version

2.12.15

jdk version

JDK8

My problem

When I learnt to use json4s to read a json file "file.json". (In book "Scala design patterns")

import org.json4s._
import org.json4s.jackson.JsonMethods._

trait DataReader {
  def readData(): List[Person]

  def readDataInefficiently(): List[Person]
}

class DataReaderImpl extends DataReader {

  implicit val formats = DefaultFormats

  private def readUntimed(): List[Person] =
    parse(StreamInput(getClass.getResourceAsStream("file.json"))).extract[List[Person]]

  override def readData(): List[Person] = readUntimed()

  override def readDataInefficiently(): List[Person] = {

    (1 to 10000).foreach(_ =>
      readUntimed())
    readUntimed()
  }
}

object DataReaderExample {
  def main(args: Array[String]): Unit = {
    val dataReader = new DataReaderImpl
    println(s"I just read the following data efficiently:${dataReader.readData()}")
    println(s"I just read the following data inefficiently:${dataReader.readDataInefficiently()}")
  }
}

It cannot compile correctly, and throw:

could not find implicit value for evidence parameter of type org.json4s.AsJsonInput[org.json4s.StreamInput]
Error occurred in an application involving default arguments.
    parse(StreamInput(getClass.getResourceAsStream("file.json"))).extract[List[Person]]

when I change json4s version in 3.6.0-M2 in sbt: "org.json4s" %% "json4s-jackson" % "3.6.0-M2"

It works well.

Why would this happen? How should I fix it in 4.0.4 or higher version?

Thank you for your Help.

1

There are 1 best solutions below

0
NIMENDAVID On

I tried many ways to solve this problem. And finally:

remove StreamInput in :

  private def readUntimed(): List[Person] = {
    val inputStream: InputStream = getClass.getResourceAsStream("file.json")
    // parse(StreamInput(inputStream)).extract[List[Person]] // this will work in 3.6.0-M2
    parse(inputStream).extract[List[Person]]
  }

and now it works !