0

I want to convert array: String to Seq[Message]...

Case class:

case class Message(name: String, sex: String)

Source:

[
    { "name": "Bean",
      "sex": "F"
    },
    {
      "name": "John",
      "sex": "M"
    }
]

Destination

Seq[Person]

How to convert?? code...

Patryk Rudnicki
  • 755
  • 1
  • 8
  • 21

1 Answers1

1

You need to use some sort of decoders/deserialisers to decode string into case class. There are tons of decoders in scala. One of my favourite is circe as it is functional and also works pretty well with scalajs.

import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._

case class Message(name: String, sex: String)

val encoded =
  """
    |[
    |    { "name": "Bean",
    |      "sex": "F"
    |    },
    |    {
    |      "name": "John",
    |      "sex": "M"
    |    }
    |]
  """.stripMargin

val decoded: Either[Error, List[Message]] = decode[List[Message]](encoded)

decoded match {
  case Right(e) => println("success: " + e)
  case Left(l) => println("failure: "+ l)
}

output:

success: List(Message(Bean,F), Message(John,M))

If you looking for plain simple compatible with java, take a look at https://github.com/FasterXML/jackson-module-scala

Also see: Scala deserialize JSON to Collection

prayagupa
  • 30,204
  • 14
  • 155
  • 192