简体   繁体   English

Scala / Play如何使用JSON读取来处理可以是字符串或数组的JSON值,并始终返回Set [String]

[英]Scala/Play How to use JSON read to handle JSON value that can be string or array and always return Set[String]

I have the following class in my play server and the JSON Reads used for validation 我的播放服务器中有以下类,JSON读取用于验证

case class Foo(name: String, link: String)

val fooReads = (
  (__ \ "name").read[String] ~
  (__ \ "link").read[String]
)(Foo.apply _)

I have changed the model to allow multiple links instead of one so i can expect array of strings in the input JSON: 我更改了模型以允许多个链接而不是一个链接,因此我可以期望输入JSON中的字符串数组:

case class Foo(name: String, link: Set[String])

val fooReads = (
  (__ \ "name").read[String] ~
  (__ \ "link").read[Set[String]] // it works this way
)(Foo.apply _)

I want to make it back compatible so it can handle JSON value of "link" with string along with array of strings 我想使其回兼容,以便它可以处理带有字符串以及字符串数组的"link" JSON值

You can use the operator orElse on json Reads to create your custom reader: 您可以在JSON Reads上使用运算符orElse来创建自定义阅读器:

val readsSet: Reads[Set[String]] = Reads.of[Set[String]].orElse(Reads.of[String].map(str => Set(str)))

val fooReads = (
  (__ \ "name").read[String] ~
  (__ \ "link").read[Set[String]](readsSet)
)(Foo.apply _)

You can use Reads.orElse combinator: 您可以使用Reads.orElse组合器:

val fooReads: Reads[Foo] = (
  (__ \ "name").read[String] ~
  (__ \ "link").read(Reads.of[String].map(str => Set(str)).
    orElse(Reads.of[Set[String]]))
)(Foo.apply _)

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

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