1

I'm attempting to convert a List of String's to a json array List using json4s library (https://github.com/json4s/json4s) :

object Convert {

  import scala.collection.JavaConversions._
  import org.json4s._
  import org.json4s.native.JsonMethods._

  val l = new java.util.ArrayList[String]()
  l.add("1")
  l.add("1")
  l.add("1")

  println(compact(render(l.toList)))


}

causes error :

l.toList is causing compiler error :

 type mismatch; found : List[String] required: org.json4s.JValue (which expands to) org.json4s.JsonAST.JValue

Does each element of the array need to be converted to a JValue ? Is there a standard method of converting a scala List[String] to json array ?

1 Answer 1

1

Json4s requires an instance of org.json4s.Formats to be in scope in order to convert (serialize) Scala types (like case classes and native collections) to JSON.

Here is my take on the Converter code you have:

object Convert {
  import scala.collection.JavaConverters._ // I prefer this to JavaConversions
  import org.json4s._
  import org.json4s.native.Serialization._ // provides write()

  implicit val formats = org.json4s.DefaultFormats 

  val l = new java.util.ArrayList[String]()
  l.add("1")
  l.add("1")
  l.add("1")

  val asJsonString = write(l.asScala)
  println(compact(parse(asJsonString)))
}

Notes:

  • I prefer JavaConverters to JavaConversions. It provides an implicitly defined asScala method to the collection that makes it more transparent in the code that there is a Java2Scala conversion taking place
  • I would also suggest using Jackson than Native given Jackson's popularity and extensive testing
Sign up to request clarification or add additional context in comments.

2 Comments

why jackson instead of native ?
It's all about what library is used to create the Json AST. To the best of my knowledge, native will use the native Json4s AST code. The Jackson will use the AST code from Jackson, which is the standard Json parsing library in Java. Given how popular and tested Jackson is, I feel it's a safer choice. In terms of the APIs nothing changes, so you can easily switch between the two.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.