简体   繁体   中英

Json string to Map in Scala --> Liftweb

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)

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM