0

This is my input structure. All the fields here are optional because it can have zero or more elements in this json string. I am fine to use liftweb or regular scala.

{
"fname" :  String,
"lname" :  String,
"age" :  String,
"gender" :  String,
"phone" :  String,
"mstatus" :  String
}

Input: (Note here "mstatus" is not available and "gender" is empty)

{
"fname" : "Thomas",
"lname" : "Peter",
"age" : "20",
"gender" : "",
"phone" : "12345
}

I want to read this Json string and to check whether the key is present and its value is not null then add into a map. My output map would like below.

val inputMap = Map(
      "fname" -> "Thomas"
      "lname" -> "Peter"
      "age" -> "20",
    "phone" -> "12345)
Revathi P
  • 77
  • 13

2 Answers2

0

Hope this can help you.

scala> val jsonString = """{
                   "fname" : "Thomas",
                   "lname" : "Peter",
                   "age" : "20",
                   "gender" : "",
                   "phone" : "12345"
                   }"""
jsonString: String =
{
                   "fname" : "Thomas",
                   "lname" : "Peter",
                   "age" : "20",
                   "gender" : "",
                   "phone" : "12345"
                   }

scala> val r = JSON.parseFull(jsonString)
   .getOrElse(Map[String,Any]())
   .asInstanceOf[Map[String,Any]].collect{
          case e : (String, Any) if(e._2 != null && !e._2.toString.isEmpty) => e
    }

Output :-

 r: scala.collection.immutable.Map[String,Any] = Map(fname -> Thomas, age -> 20, lname -> Peter, phone -> 12345)
Puneeth Reddy V
  • 1,538
  • 13
  • 28
  • I am getting run time exception Exception in thread "main" java.lang.ClassCastException: scala.collection.immutable.HashMap$HashTrieMap cannot be cast to scala.collection.mutable.Map – Revathi P Mar 22 '18 at 14:59
  • I double checked it, I'm not able to reproduce this issue. – Puneeth Reddy V Mar 23 '18 at 09:30
0

You can use the Spary Json lib to convert and handle easy way.

val jsonString: String =
    """{
      |   "fname" : "Thomas",
      |   "lname" : "Peter",
      |   "age" : "20",
      |   "gender" : "",
      |   "phone" : "12345"
      |}""".stripMargin

parse the json and get the map key value like this,

import spray.json._
val jsonMapKeyVal: Map[String, String] =
    jsonString.parseJson
      .asJsObject
      .fields
      .map {
        case (k, JsString(v)) => k -> v
      }
      .filter(_._2!="")

Result:

Map(fname -> Thomas, age -> 20, lname -> Peter, phone -> 12345)

Reference: https://github.com/spray/spray-json

Rumesh Krishnan
  • 443
  • 4
  • 16
  • Hi, @Rumesh Krishnan Thank you. I am already parsing another Json string in the same program using liftweb.json. It won't be nice/good to use multiple json format in the same program. I would apreciate similar one for liftweb.json – Revathi P Mar 22 '18 at 19:49