-2

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.

Gaël J
  • 11,274
  • 4
  • 17
  • 32
Senthil
  • 39
  • 3
  • 5
    Which json lib are you using? What have you already tried? What are the encountered errors? – cchantep Jun 13 '22 at 07:10
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jun 13 '22 at 12:13
  • I will get Input JSON like employee: { name: "test", employeeBranch: ["CSE", "IT", "ECE"] } from UI. And I need to process it and I need to make output json like below by using scala Employee: { Name: "test", EmployeeBranch:[{"branch": "CSE"}, {"branch": "IT"}, {"branch": "ECE"}] } – Senthil Jun 13 '22 at 12:46
  • I will be using play.api.json – Senthil Jun 13 '22 at 13:16

1 Answers1

1

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.

Tim
  • 26,753
  • 2
  • 16
  • 29
  • 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. – Senthil Jun 13 '22 at 09:26
  • I edited in questions also for case class – Senthil Jun 13 '22 at 09:36