arraysjsonscalaspray-json

How to convert a sequence of Tuples into JSON array in spray


I have an array of student IDs which is dynamic in scala.

val studentIds = Seq(1,2,3,4....)

I should convert them into a JSON array in Spray JSON.

like

[
 {"student_id" : 1 },
 {"student_id" : 2 },
 {"student_id" : 3 },
]

How to do it without a case class?


Solution

  • You can use Maps. Each map will be translated directly to an json object.

    import spray.json._
    import DefaultJsonProtocol._
    
    val studentIds = Seq(1,2,3,4).map(s => Map("student_id" -> s))
    
    println(studentIds.toJson)