scala 按顺序解析 json 个对象
scala parse json objects in order
我有以下 json 输入,我试图按顺序解析名称字段
scala> result
res6: play.api.libs.json.JsValue = {"L0":
{"name":"FASHION","id":"50000"},"L1":{"name":"ACCESSORIES AND TRAVEL","id":"51000"},"L2":{"name":"FASHION ACCESSORIES","id":"51001"},"L3":{"name":"MENS FASHION ACCESSORIES","id":"51100"},"L4":{"name":"MENS HATS","id":"51204"}}
scala> result \ "name"
res5: Seq[play.api.libs.json.JsValue] = List("ACCESSORIES AND TRAVEL", "MENS HATS", "MENS FASHION ACCESSORIES", "FASHION ACCESSORIES", "FASHION")
我正在尝试的是按顺序获取这些名称,例如
List("FASHION", "ACCESSORIES AND TRAVEL", "FASHION ACCESSORIES", "MENS FASHION ACCESSORIES", "MENS HATS")
有没有办法通过 play Json 库来实现?
With Play JSON 我总是用 case classes
。所以你的例子看起来像:
进口play.api.libs.json._
val json = """{"L0":
{"name":"FASHION","id":"50000"},"L1":{"name":"ACCESSORIES AND TRAVEL","id":"51000"},"L2":{"name":"FASHION ACCESSORIES","id":"51001"},"L3":{"name":"MENS FASHION ACCESSORIES","id":"51100"},"L4":{"name":"MENS HATS","id":"51204"}}
"""
case class Element(id: String, name: String)
object Element {
implicit val jsonFormat: Format[Element] = Json.format[Element]
}
Json.parse(json).validate[Map[String, Element]] match {
case JsSuccess(elems, _) => println(elems.toList.sortBy(_._1).map(e => e._2.name))
case other => println(s"Handle exception $other")
}
这为您提供的是,您可以按键对结果进行排序 - 解决方案中丢失的信息。
我有以下 json 输入,我试图按顺序解析名称字段
scala> result
res6: play.api.libs.json.JsValue = {"L0":
{"name":"FASHION","id":"50000"},"L1":{"name":"ACCESSORIES AND TRAVEL","id":"51000"},"L2":{"name":"FASHION ACCESSORIES","id":"51001"},"L3":{"name":"MENS FASHION ACCESSORIES","id":"51100"},"L4":{"name":"MENS HATS","id":"51204"}}
scala> result \ "name"
res5: Seq[play.api.libs.json.JsValue] = List("ACCESSORIES AND TRAVEL", "MENS HATS", "MENS FASHION ACCESSORIES", "FASHION ACCESSORIES", "FASHION")
我正在尝试的是按顺序获取这些名称,例如
List("FASHION", "ACCESSORIES AND TRAVEL", "FASHION ACCESSORIES", "MENS FASHION ACCESSORIES", "MENS HATS")
有没有办法通过 play Json 库来实现?
With Play JSON 我总是用 case classes
。所以你的例子看起来像:
进口play.api.libs.json._
val json = """{"L0":
{"name":"FASHION","id":"50000"},"L1":{"name":"ACCESSORIES AND TRAVEL","id":"51000"},"L2":{"name":"FASHION ACCESSORIES","id":"51001"},"L3":{"name":"MENS FASHION ACCESSORIES","id":"51100"},"L4":{"name":"MENS HATS","id":"51204"}}
"""
case class Element(id: String, name: String)
object Element {
implicit val jsonFormat: Format[Element] = Json.format[Element]
}
Json.parse(json).validate[Map[String, Element]] match {
case JsSuccess(elems, _) => println(elems.toList.sortBy(_._1).map(e => e._2.name))
case other => println(s"Handle exception $other")
}
这为您提供的是,您可以按键对结果进行排序 - 解决方案中丢失的信息。