这是我的输入结构。此处的所有字段都是可选的,因为它可以在此 json 字符串中包含零个或多个元素。我可以使用liftweb或常规scala。
{
"fname" : String,
"lname" : String,
"age" : String,
"gender" : String,
"phone" : String,
"mstatus" : String
}
输入:(注意此处"mstatus"不可用,"gender"为空(
{
"fname" : "Thomas",
"lname" : "Peter",
"age" : "20",
"gender" : "",
"phone" : "12345
}
我想读取这个 Json 字符串并检查键是否存在并且其值不为 null,然后添加到地图中。我的输出地图如下所示。
val inputMap = Map(
"fname" -> "Thomas"
"lname" -> "Peter"
"age" -> "20",
"phone" -> "12345)
希望这能帮助你。
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
}
输出:-
r: scala.collection.immutable.Map[String,Any] = Map(fname -> Thomas, age -> 20, lname -> Peter, phone -> 12345)
您可以使用 Spary Json 库来转换和处理简单的方法。
val jsonString: String =
"""{
| "fname" : "Thomas",
| "lname" : "Peter",
| "age" : "20",
| "gender" : "",
| "phone" : "12345"
|}""".stripMargin
解析 JSON 并像这样获取映射键值,
import spray.json._
val jsonMapKeyVal: Map[String, String] =
jsonString.parseJson
.asJsObject
.fields
.map {
case (k, JsString(v)) => k -> v
}
.filter(_._2!="")
结果:
Map(fname -> Thomas, age -> 20, lname -> Peter, phone -> 12345)
参考: https://github.com/spray/spray-json