Reputation: 27
I'm new in Scala and do not know how to deal with this Json with json4s:
After parsing the json and extracting the following json through:
val data = json \\ "someKey"
I have a Json like this:
[{"Id":14706061,
"Rcvr":1,
"HasSig":true,
"Sig":80},
{"Id":3425490,
"Rcvr":1,
"HasSig":false,
"Sig": 80}]
Printing it to the console, it returns:
JArray(List(JObject(List((Id,JInt(14706061)), (Rcvr,JInt(1)), (HasSig,JBool(true)), (Sig,JInt(80), Id,JInt(3425490)), (Rcvr,JInt(1)), (HasSig,JBool(false)), (Sig,JInt(80) ))
So, after that I used:
println("show values: " + data.values)
And had:
List(Map(Id -> 14706061, Rcvr -> 1, HasSig -> true, Sig -> 80), Map(Id -> 3425490, Rcvr -> 1, HasSig -> false, Sig -> 80))
But I don't know how to extract each Map from each position of the List.
I also tried to extract to a case class but I had 0 entries:
case class Example (Id: BigInt, Rcvr: Int, HasSig: Boolean, Sig: Int)
case class ExampleList (examples: List[Example])
implicit val formats = DefaultFormats.strict
val dataList = data.extract[ExampleList]
Thanks in advance for your help
PD. If I assign:
val dataList = data.values
The type of dataList (with getClass) is: class scala.collection.immutable.$colon$colon
After the:
val data = json \\ "someKey"
I put:
val dataList = data.extract[JArray]
val examples = dataList.values
It returns an iterable Array with its Maps iterable, so fixed.
Checked with:
println("number of elements: " + examples.length)
and
println("show each item: " + examples.foreach(println))
Thanks for taking your time in reading.
Upvotes: 1
Views: 4847
Reputation: 1428
If you want to extract into a Case Class instead of a Map, the correct type for extraction is List[Example]
, instead of ExampleList
.
ExampleList
has an attribute examples
, your json doesn't. That is why you got an empty list.
import org.json4s.native.JsonMethods._
import org.json4s._
implicit val formats = DefaultFormats
val str = """[{"Id":14706061,
"Rcvr":1,
"HasSig":true,
"Sig":80},
{"Id":3425490,
"Rcvr":1,
"HasSig":false,
"Sig": 80}]"""
case class Example (Id: BigInt, Rcvr: Int, HasSig: Boolean, Sig: Int)
val json = parse(str)
val examples = json.extract[List[Example]]
Upvotes: 4
Reputation: 31
Hope the below code helps.
enter code here
val iList = List(Map("Id" -> 14706061, "Rcvr" -> 1, "HasSig" -> "true", "Sig" -> 80),
Map("Id" -> 3425490, "Rcvr" -> 1, "HasSig" -> false, "Sig" -> 80))
for(i <-0 until iList.size){val lMap = iList(i)println("Id: " + lMap("Id"))}
Upvotes: 0