Domanda

I am trying to construct json string from array. I am able to get json string format using JsonAST as below :

import net.liftweb.json.JsonAST
import net.liftweb.json.JsonDSL._
import net.liftweb.json.Printer._

val map = Map("a" -> "b", "c" -> "d")
val c = compact(JsonAST.render(map)) 
println(c) //op : {"a":"b","c":"d"}

When i try to do the same thing with array, it is throwing below error : required: net.liftweb.json.JsonAST.JValue

I am looking for serializing an array like val a = Array(1,2,3)

What is the common way of getting json response, which supports all data structures?

È stato utile?

Soluzione

I use json4s (which happens to use lift-json under the hood):

import org.json4s.native.Serialization.write
import org.json4s.DefaultFormats

val a = Array(1,2,3,4,5)

implicit val formats = DefaultFormats
println(write(a))  // [1,2,3,4,5]

It can also serialize more complex values:

case class Test(map: Map[String, Int], arr: Array[Int])
val t = Test(Map("one" -> 1, "two" -> 2), Array(1, 2, 3, 4, 5))
println(write(t))  // {"map":{"one":1,"two":2},"arr":[1,2,3,4,5]}

Altri suggerimenti

You just need to convert the array to a List, looks as if liftweb AST doesn't define an implicit conversion for raw array types...so something like this:

scala> val array = Array(1,2,3,4,5)
scala>  val c = compact(JsonAST.render(array.toList))

(Note that addition of "toList") Works fine.

Hope this helps.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top