Puneeth Reddy V
Puneeth Reddy V

Reputation: 1578

Create a list with empty map

I have a JSON string which is parsed and a typecaseted to a map. I'm using this map to get a List[Map[String, Any]]. Here to make my code error free I have used getOrElse while type casting.

JSON string looks similar to

{
  "map-key" : [
     {
       "list-object-1-key" : "list-object-1-value"
     },
     {
       "list-object-2-key" : "list-object-2-value"
     }, 
  ]
} 

My code

val json = JSON.parseFull(string) match {
    case Some(e) =>
          val list = e.asInstanceOf[Map[String, Any]]
                  .getOrElse("map-key", List[Map[String,Any]]) // Error here
          val info = list.asInstanceOf[List[Map[String, Any]]]
          //iterate over each element in the list and perform my operations
   case None => string
}

I can understand that whenever there is no result present in list object then info object is repeated code.

How can I improve this programme by giving the default value to list object?

Upvotes: 0

Views: 992

Answers (3)

Evgeny
Evgeny

Reputation: 1770

Do it in more functional way, without asInstanceOf:

    val parsed = JSON.parseFull(string)
    parsed match {
        case Some(e: Map[String, Any]) =>
            e.get("map-key") match {
                case Some(a: List[Any]) =>
                    a.foreach {
                        case inner: Map[String, Any] => println(inner.toList)
                    }
                case _ =>
            }
        case None => string
    }

Upvotes: 2

Miguel
Miguel

Reputation: 1211

Your default value is wrong. You're passing a type, not an empty list.

e.asInstanceOf[Map[String, Any]].getOrElse("map-key", List.empty[Map[String,Any]])

Upvotes: 0

Basil Battikhi
Basil Battikhi

Reputation: 2668

Unfortunately i don't have the environment at this machine but try something like that

first thing you need to convert json to map

def jsonStrToMap(jsonStr: String): Map[String, Any] = {
  implicit val formats = org.json4s.DefaultFormats

  parse(jsonStr).extract[Map[String, Any]]
}

and the second thing you will need to iterate over map to get values of list

val list= jsonStrToMap.map{ case(k,v) => (k.getBytes, v) }. toList

Upvotes: 0

Related Questions