使play-json对于Option [T]类型的空字符串读取为None [英] make play-json read the empty string as None for a type of Option[T]
问题描述
我正在尝试使用play-json从GitHub API解析json,并在Pull Requests上遇到merge_commit_sha
字段的问题(顺便说一句,我知道此字段已弃用,但不想讨论在这个解析问题中!).不幸的是,在某些情况下,merge_commit_sha
字段作为空字符串返回:
I'm attempting to parse json from the GitHub API with play-json, and encountering a problem with the merge_commit_sha
field on Pull Requests (incidentally, I know this field is deprecated, but don't want to discuss that in this parsing problem!). Unfortunately merge_commit_sha
field comes back as the empty string in some cases:
"merge_commit_sha": ""
这是我有一个
I have an implicit Format[ObjectId]
, which does not tolerate the empty string, because that's not a valid value for a Git hash id. I'm also using a play-json macro-generated Read[PullRequest]
, which I'd like to keep on using, in preference to individually declaring reads for every single field on pull requests.
正如我已经声明该字段为Option一样,我希望将"merge_commit_sha": ""
读取为值None
,但这不是当前发生的情况-存在字符串,因此Format[ObjectId]
被调用,并返回JsFailure
.
As I've declared the field to be an Option, I'd like "merge_commit_sha": ""
to be read as the value None
, but this is not what currently happens - a string is present, so the Format[ObjectId]
is invoked, and returns a JsFailure
.
我尝试过的一件事是声明具有所需行为的隐式Format[Option[ObjectId]]
,但似乎并没有被宏生成的Read[PullRequest]
所使用.
One thing I tried was declaring an implicit Format[Option[ObjectId]]
with the required behaviour, but it didn't seem to get used by the macro-generated Read[PullRequest]
.
推荐答案
您可以定义自定义使用Json.format[MyType]
使用Scala宏. 您也许可以加入其中.尽管为这个case class
'扩展'宏似乎是错误的.
Using Json.format[MyType]
uses a Scala macro. You may be able to hook into that. Although, 'extending' a macro for this one case class
just seems wrong.
自定义读取和写入可能有点样板式"并且很无聊,但是它们有其优势.
Custom Reads and Writes might be a little 'boilerplate-like' and boring, but they have their upsides.
例如,如果您的json上有一堆新字段,则在将其验证或转换为case class
时不会得到JsError
.您只需从JSON中获取所需的内容并创建对象.它还可以将您的内部模型与您所消费的内容区分开来,在某些情况下,这是首选.
For example if your json has a bunch of new fields on it, you wont get a JsError
when validating or transforming it to a case class
. You only take what you need from the JSON and create objects. It also allows for a separation between your internal model and what you're consuming, which in some cases is preferred.
我希望这会有所帮助,
Rhys
编辑
Rhys
EDIT
使用其他一些JSON库之后,我可能已经找到了您想要的东西. 我知道这个问题是在播放JSON之后专门问的.
After using some other JSON libs I may have found what you are looking for. I know the question was asking specifically after Play JSON.
如果您能够摆脱Play JSON,请查看 spray-json-shapeless 特别是JsNullBehaviour
和JsNullNotNone
If you're able to move away from Play JSON, Look at spray-json-shapeless specifically JsNullBehaviour
and JsNullNotNone
REF.
这篇关于使play-json对于Option [T]类型的空字符串读取为None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!