Skip to content

Instantly share code, notes, and snippets.

@koljamaier
Created June 10, 2018 12:04
Show Gist options
  • Save koljamaier/9186cd93729b39d98fe4ba44ab4c1cc0 to your computer and use it in GitHub Desktop.
Save koljamaier/9186cd93729b39d98fe4ba44ab4c1cc0 to your computer and use it in GitHub Desktop.
This snippet show the usage of jacksons fasterxml library in scala for my use case
package recfun.week3
import com.fasterxml.jackson.databind.JsonNode
import scala.collection.JavaConversions._
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.databind.ObjectMapper
import scala.util.parsing.json.JSON
object JsonParsing {
def main(args: Array[String]) {
val jsonString =
"""
|{"body":{
| "method":"string",
| "events":"string",
| "clients":"string",
| "parameter":"string",
| "channel":"string",
| "metadata":[{
| "meta1":"stri1ng",
| "meta2":"string",
| "meta3":"string",
| "lol" :[{
| "zack": "bumm"
| },
| {
| "zack": "bumm232"
| }
| ]
| },
| {
| "meta1":"dasd",
| "meta2":"ddd",
| "meta3":"stridng",
| "lol" :[{
| "zack": "bumm"
| },
| {
| "zack": "bumm232"
| }
| ]
| }
| ],
| "tester": {
| "test1": "dda",
| "tee": {"tetl": "b", "waku": "j"}
| }
|},
|"timestamp":"string"}
""".stripMargin
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
// good to use for "flat" maps
val jsonMap = mapper.readValue(jsonString, classOf[Map[String, String]])
val t = jsonMap.get("test")
// get a tree of JsonNode types
val rootNode: JsonNode = mapper.readTree(jsonString)
println("size " + rootNode.size) // 2 -> "body" & "timestamp"
println("size " + rootNode.get("body").size) // 7
def parseJsonToListMap(root: JsonNode, key: String): List[Map[String, String]] = {
val jNode = root.findValue(key) // similair to json path function $..*.key
if (jNode.isArray) parseJsonArrayToListMap(jNode.elements.toList)
else List(extractMap(jNode))
}
def extractMap(root: JsonNode): Map[String, String] = {
val l = for (i <- root.fields()) yield {
i.getKey -> mapper.writeValueAsString(i.getValue)
}
l.toMap
}
def parseJsonArrayToListMap(jsonArray: List[JsonNode]): List[Map[String, String]] = {
jsonArray match {
case x :: xs => extractMap(x) :: parseJsonArrayToListMap(xs)
case List() => List()
}
}
val parsed = parseJsonToListMap(rootNode, "tester")
println(parsed.head("tee"))
val parsed1 = parseJsonToListMap(rootNode, "metadata")
println(parsed1.head("meta1"))
println(parsed1.tail.head("meta1"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment