简体   繁体   English

Scala Json-Json列表

[英]Scala Json - List of Json

I have the below code and the output from my program. 我有以下代码和程序的输出。 However, I could not create a List of Json (desired output) given below. 但是,我无法创建下面给出的Json List (期望的输出)。 What kind changes do I need to do in the existing code? 我需要在现有代码中进行哪些更改?

case class Uiresult(AccountNo: String, Name: String)

val json = parse(jsonString)
val elements = (json \\ "_source").children
for (acct <- elements) {
  val m = acct.extract[Source]
  val res = write(Uiresult(m.accountNo, (m.firstName + m.lastName))
  println(res)
}

Output from current program: 当前程序的输出:

{"AccountNo":"1234","Name":"Augustin John"}
{"AccountNo":"1235","Name":"Juliet Paul"}
{"AccountNo":"1236","Name":"Sebastin Arul"}

Desired output: 所需的输出:

[
{"AccountNo":"1234","Name":"Augustin John"},
{"AccountNo":"1235","Name":"Juliet Paul"},
{"AccountNo":"1236","Name":"Sebastin Arul"}
]

To create a list for the for comprehension, use the yield keyword. 要创建供理解的列表,请使用yield关键字。 This will return the values from the iterations and create a list for you, which you then can assign to a val . 这将从迭代中返回值,并为您创建一个列表,然后您可以将其分配给val

val list = for (acct <- elements) yield {
  val m = acct.extract[Source]
  val res = write(Uiresult(m.accountNo, (m.firstName + m.lastName))
  res
}

This can be written even shorter, 这可以写得更短,

val list = for (acct <- elements) yield {
  val m = acct.extract[Source]
  write(Uiresult(m.accountNo, (m.firstName + m.lastName))
}

The type of list ( Array , List , Seq , etc.) will be determined by the type of elements . 列表的类型( ArrayListSeq等)将由elements的类型确定。 Other data structures such as set dictionaries are also possible to use in this way. 其他数据结构(例如集合字典)也可以以此方式使用。


To print the output into the exact format as in the "desired output" above, use mkString . 要将输出打印为与上述“所需输出”相同的格式,请使用mkString

println(list.mkString("[\n", ",\n", "\n]"))

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

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