0

I have a scala app in which I'm using json4s to do some json manipulation. I have a few fields that I would like to convert into a new object.

For example I have the following:

"start_datetime":"2016-12-11T01:00:05+0000",
"type":"absolute",
"start":"5",
"type":"offset"

That would like to make into:

"time":[
 {
    "type":"absolute",
    "start_datetime":"2016-12-11T01:00:05+0000"
 },
 {
    "type":"offset",
    "start":"10"
 }
]

Any way I can do this using json4s?

Steve Y.
  • 87
  • 1
  • 6

1 Answers1

2

The below snippet uses native json4s DSL

A Json object is formed by tuples chained together by method ~ and the Json Array is created by creating a Sequence object in Scala. Other primitive types like String, Number, Boolean are mapped to the corresponding types in scala

import org.json4s.native.JsonMethods._
import org.json4s.JsonDSL._

val json = "time" -> Seq(
("type" -> "absolute") ~ ("start_datetime" -> "2016-12-11T01:00:05+0000"),
("type" -> "offset") ~ ("start" -> "10")
)

scala> compact(render(json))
res3: String = {"time":[{"type":"absolute","start_datetime":"2016-12-11T01:00:05+0000"},{"type":"offset","start":"10"}]}
rogue-one
  • 11,259
  • 7
  • 53
  • 75