Home > database >  How to convert JsonObject (gson) to Map Object directly in Scala?
How to convert JsonObject (gson) to Map Object directly in Scala?

Time:12-29

I want to know how to convert JsonObject (gson) to Map, JsonArray to Seq in Scala? I've already checked this answer, which uses jackson library, but I have to convert from JsonObject/Array to plain String first, then convert to Map, Arraystrong text. Below is my current code:

import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.common.collect.ImmutableMap
import com.google.gson.{Gson, JsonObject}


object test {
  def main(args: Array[String]): Unit = {

    var json: String = "{\"itemScores\":[{\"item\":\"37064\",\"score\":0.0},{\"item\":\"1365\",\"score\":0.0}]}"
    var jsonObject = new Gson().fromJson(json, classOf[JsonObject])
    println(jsonObject) //{"itemScores":[{"item":"37064","score":0.0},{"item":"1365","score":0.0}]}
    println(jsonObject.getClass) //class com.google.gson.JsonObject

    var list1 = jsonObject.get("itemScores")
    println(list1) //[{"item":"37064","score":0.0},{"item":"1365","score":0.0}]
    println(list1.getClass) //class com.google.gson.JsonArray

    var listConvert: Seq[Map[Any, Any]] = Seq[Map[Any, Any]]() //Convert from Json Array to Scala Seq
    var mapConvert: Map[String, Seq[Any]] = Map[String, Seq[Any]]() //Convert from Json Object to Scala Map

    val mapper = new ObjectMapper()
    mapper.registerModule(DefaultScalaModule)

    mapConvert = mapper.readValue(jsonObject.toString, classOf[Map[String, Seq[Any]]])
    listConvert = mapper.readValue(list1.toString, classOf[Seq[Map[Any, Any]]])
    println(mapConvert) //Map(itemScores -> List(Map(item -> 37064, score -> 0.0), Map(item -> 1365, score -> 0.0)))
    println(listConvert) //List(Map(item -> 37064, score -> 0.0), Map(item -> 1365, score -> 0.0))
    
    for ( i <- listConvert) {
       println(i.get("item"))
       }
   }

Is there any way that I can convert directly from JsonObject to Map, JsonArray to Seq in Scala? My final goal is to iterate through JSON Object/Array

CodePudding user response:

If your goal is to iterate over unknown data, you can do it directly on the GSON objects.

For an object:

val jsonObject: JsonObject = ???

// Get the content and then iterate
val entries: Set[Entry [String, JsonElement]] = jsonObject.entrySet().asScala

// Or directly view the object as a map and then iterate
val map: Map[String, JsonElement] = jsonObject.asMap().asScala

For an array:

val jsonArray: JsonArray = ???

// As iterator
val iterable: Iterator[JsonElement] = jsonArray.iterator()

// Or directly as a list
val list: Seq[JsonElement] = jsonArray.asList().asScala
  • Related