How can I transform a Map to a case class in Scala?

后端 未结 5 1851
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 21:00

If I have a Map[String,String](\"url\" -> \"xxx\", \"title\" -> \"yyy\"), is there an way to generically transform it into a case class Image(url:St

5条回答
  •  别那么骄傲
    2020-12-13 21:30

    Not a full answer to your question, but a start…

    It can be done, but it will probably get more tricky than you thought. Each generated Scala class is annotated with the Java annotation ScalaSignature, whose bytes member can be parsed to give you the metadata that you would need (including argument names). The format of this signature is not API, however, so you'll need to parse it yourself (and are likely to change the way you parse it with each new major Scala release).

    Maybe the best place to start is the lift-json library, which has the ability to create instances of case classes based on JSON data.

    Update: I think lift-json actually uses Paranamer to do this, and thus may not parse the bytes of ScalaSignature… Which makes this technique work for non-Scala classes, too.

    Update 2: See Moritz's answer instead, who is better informed than I am.

提交回复
热议问题