Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save learner-long-life/38f207816554b8bbffef58aa7cfebcf1 to your computer and use it in GitHub Desktop.
Save learner-long-life/38f207816554b8bbffef58aa7cfebcf1 to your computer and use it in GitHub Desktop.
How to iterate over a Jackon JsonNode / Java Map Entry iterator in Scala
import scala.collection.JavaConverters._
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.{JsonNodeFactory, MissingNode, ObjectNode}
val jf = new JsonFactory(true)
val o = new ObjectNode(jf)
o.put("yellow","banana")
for (v <- o.fields.asScala) { println(v.getKey(),v.getValue()) }
// (yellow,"banana")
@seyfer
Copy link

seyfer commented Apr 9, 2018

And if we have an array in the JSON, it will be not JsonNode, but ArrayNode. To iterate it, use elements instead of fields
o.elements.asScala

@seyfer
Copy link

seyfer commented Sep 20, 2019

Also asScala creates a Scala-like collection which can be chained with .foreach, .map, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment