Create Json from scala object with List

1.8k views Asked by At

I need to create a Json with 2 elements. The First element is a List and the second element is simple key-value pair. My output looks as follows:

"{
  "tables":[
  {"table": "sn: 2134"},
  {"table": "sn: 5676"},
  {"table": "sn: 4564"},
  ],
  "paid": 219
  }" 

In the example , the first element is tables which is List of table. The second element is paid.

I tried it using play.api.libs.json lib , but stuck while adding second element.

My code looks as follows:

 case class Input(table:String){
    override def toString = s""""table" : "sn: $table""""
  }
implicit val userFormat = Json.format[Input]
val inputsSeq = Seq(Input(table1),Input(table2),Input(table3))
val users = Json.obj("tables" -> inputsSeq)
println(users)

This code print Json as :

 "{
      "tables":[
      {"table": "sn: 2134"},
      {"table": "sn: 5676"},
      {"table": "sn: 4564"},
      ]
}

I am not sure, how to add the second element in this json. any suggestion how to resolve this.

1

There are 1 answers

3
DeadNight On

Json.obj accepts multiple pairs of (String, JsValueWrapper) as its arguments:

object Json {
  ...
  def obj(fields: (String, JsValueWrapper)*): JsObject = JsObject(fields.map(f => (f._1, f._2.asInstanceOf[JsValueWrapperImpl].field)))
  ...
}

So you can add both elements like this:

val users = Json.obj("tables" -> inputsSeq, "paid" -> 219)