如何将列表[字符串]转换为Scala中的列表[对象]

发布于 2025-02-06 20:32:51 字数 781 浏览 1 评论 0原文

我需要从一个list [String]更改为list [MyObject]在Scala中。

例如,JSON输入就像下面的

employee: {
  name: "test",
  employeeBranch: ["CSE", "IT", "ECE"]
}

输出一样,

Employee: {
  Name: "test",
  EmployeeBranch:[{"branch": "CSE"}, {"branch": "IT"}, {"branch": "ECE"}]
}

输入案例类:

Class Office(
name: Option[String],
employeeBranch: Option[List[String]])

输出案例类:

Class Output(
Name: Option[String],
EmployeeBranch: Option[List[Branch]])

case class Branch(
branch: Option[String])

这是要求。

I need to change from one List[String] to List[MyObject] in scala.

For example,JSON input is like below

employee: {
  name: "test",
  employeeBranch: ["CSE", "IT", "ECE"]
}

Output should be like this,

Employee: {
  Name: "test",
  EmployeeBranch:[{"branch": "CSE"}, {"branch": "IT"}, {"branch": "ECE"}]
}

Input case class:

Class Office(
name: Option[String],
employeeBranch: Option[List[String]])

Output case class:

Class Output(
Name: Option[String],
EmployeeBranch: Option[List[Branch]])

case class Branch(
branch: Option[String])

This is the requirement.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

诠释孤独 2025-02-13 20:32:51

在不知道特定JSON库的详细信息的情况下,很难回答,但是对象可能表示为MAP。因此,要将列表[String]转换为list [MAP [String,String]]您可以做到这一点:

val list = List("CSE", "IT", "ECE")
val map = list.map(x => Map("branch" -> x))

这给出了

List(Map(branch -> CSE), Map(branch -> IT), Map(branch -> ECE))

应该转换为所需的JSON。

It is hard to answer without knowing details of the particular JSON library, but an Object is probably represented as a Map. So to convert a List[String] to a List[Map[String, String]] you can do this:

val list = List("CSE", "IT", "ECE")
val map = list.map(x => Map("branch" -> x))

This gives

List(Map(branch -> CSE), Map(branch -> IT), Map(branch -> ECE))

which should convert to the JSON you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文