简体   繁体   English

Scala循环对象列表

[英]Scala loop list of object


I have a list of JsObject like: 我有一个像这样的JsObject列表:

[{
  "a":"test1",
  "b": 2,
  "c": 5,
  "errors": "Error example"
}]

I would like to get something like this a:List[Option[String]], b: List[Option[Int]] and so on. 我想得到这样的东西a:List[Option[String]], b: List[Option[Int]] ,依此类推。 I need an option since not all the fields are alway present. 我需要一个选择,因为并非所有字段都始终存在。
My code is: 我的代码是:

jsObjList.map(js => {
  val a = (js \ "a").asOpt[String]
  val b = (js \ "b").asOpt[Int]
  val c = (js \ "c").asOpt[Int]
  val er= (js \ "errors").asOpt[String]
  (a, b, er)
})

I read about unzip and unzip3 but I haven't found a generic function. 我读到有关unzipunzip3但是我没有找到通用函数。

PS I am using Scala Play for the json parsing PS我正在使用Scala Play进行json解析


Thanks for your help! 谢谢你的帮助!

Class to extract values from raw JSON. 从原始JSON提取值的类。

case class Foo(a: Option[String], b: Option[Int], c: Option[Int],errors: Option[String])

object Foo {
  // Automatically generate json reader and writer for the class Foo
  implicit val format = Json.format[Foo]
}

Keeping the implicit value in companion object of Foo will make the Scala to pick up the implicit when required automatically. 将隐式值保留在Foo的伴随对象中将使Scala在需要时自动选择隐式值。

Code to parse JSON into list of case class instances 将JSON解析为案例类实例列表的代码

 payload.validate[List[Foo]]

Use validateOpt in case you expect any parse error 如果您期望任何解析错误,请使用validateOpt

payload.validateOpt[List[Foo]]

Scala REPL 斯卡拉REPL

scala> :paste
// Entering paste mode (ctrl-D to finish)


val str = """
[{
  "a":"test1",
  "b": 2,
  "c": 5,
  "errors": "Error example"
}]
"""

// Exiting paste mode, now interpreting.

str: String =
"
[{
  "a":"test1",
  "b": 2,
  "c": 5,
  "errors": "Error example"
}]
"

scala> val payload = Json.parse(str)
payload: play.api.libs.json.JsValue = [{"a":"test1","b":2,"c":5,"errors":"Error example"}]

scala> case class Foo(a: Option[String], b: Option[Int], c: Option[Int],errors: Option[String])
defined class Foo

scala> implicit val format = Json.format[Foo]
format: play.api.libs.json.OFormat[Foo] = play.api.libs.json.OFormat$$anon$1@53a0b0a3

scala> payload.validate[List[Foo]]
res5: play.api.libs.json.JsResult[List[Foo]] = JsSuccess(List(Foo(Some(test1),Some(2),Some(5),Some(Error example))),)

You can parse JSON as a Scala case class with a companion object containing a special val called implicit val format = Json.format[*your class*] . 您可以将JSON解析为Scala案例类,并带有一个包含特殊val的伴随对象,该特殊val称为implicit val format = Json.format[*your class*]

Here's an example similar to yours: 这是一个类似于您的示例:

import play.api.libs.json.Json

val body =
  """{
    |  "a":"my string",
    |  "b": 1,
    |  "c": 2
    |}
  """.stripMargin

val body2 =
  """{
    |  "a":"my string",
    |  "c": 5
    |}
  """.stripMargin

case class MyClass(a: Option[String], b: Option[Int], c: Option[Int])

object MyClass {
  implicit val format = Json.format[MyClass]
}

Using this, calling Json.parse(body).as[MyClass] gives: 使用此方法,调用Json.parse(body).as[MyClass]给出:

res0: MyClass = MyClass(Some(my string),Some(2),Some(5))

Calling this Json.parse function with missing fields (assuming they are optional), such as Json.parse(body2).as[MyClass] gives: 在缺少字段的情况下调用此Json.parse函数(假设它们是可选的),例如Json.parse(body2).as[MyClass]给出:

res1: MyClass = MyClass(Some(my string),None,Some(5))

If one of the missing fields is not Optional, this parse will not work. 如果缺少的字段之一不是“可选”,则此解析将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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