Accessing inner JSON field in Scala -
i have json string as
{ "whatsnew" : { "oldnotificationclass" : "whatsnewnotification", "notificationevent" : { ..... }, "result" : { "notificationcount" : 10 ..... } }, ...... "someempty": { }, ...... } i trying notificationcount field using json4s in scala follow notificationcount coming empty all. help?
update if pair empty how can handle empty condition , continue loop?
function returning json string file
def getdata(): map[string, anyref] = { val jsonstring = scala.io.source.frominputstream(this.getclass.getresourceasstream("/sample.json")).getlines.mkstring val jsonobject = parse( s""" $jsonstring """) jsonobject.values.asinstanceof[map[string, anyref]] } code fields
val mymap: map[string, anyref] = mydataloader.getdata for((key, value) <- mymap) { val id = key val eventjsonstr: string = write(value.asinstanceof[map[string, string]] "notificationevent") val resultjsonstr: string = write(value.asinstanceof[map[string, string]] "result") //val notificationcount: string = write(value.asinstanceof[map[string, map[string, string]]] "notificationcount") }
you can use path , extract so:
val count: int = (parse(jsonstring) \ "whatsnew" \ "result" \ "notificationcount").extract[int] you need import .extract[int] work:
implicit val formats = defaultformats to in loop:
parse(jsonstring).children.map { child => val count: int = (child \ "result" \ "notificationcount").extract[int] ... }
Comments
Post a Comment