我正在为 elm (0.19.1) 编写一个 JSON 解码器。我传入的 jsonValue
是一个空对象{}
。如何将该值解码为类型(此处NoPayload
)?
我尝试在解码JD.string
器的帮助下对其进行解码:
JD.string
|> JD.andThen
(\str ->
if str == "{}" then
JD.succeed NoPayload
else
JD.fail "Failed to decode non-empty payload to NoPayload decoder"
)
Run Code Online (Sandbox Code Playgroud)
但这导致了一个错误:
Problem with the given value:
{}
Expecting a STRING
Run Code Online (Sandbox Code Playgroud)
或者,我正在试验JD.null
和JD.dict
,但找不到解决方案。
您可以通过使用dict
将 JSON 对象转换为字典来验证空对象,然后验证字典中没有键:
import Dict
import Json.Decode as JD exposing (Decoder)
emptyJsonDecoder : Decoder Payload
emptyJsonDecoder =
JD.dict JD.int
|> JD.andThen
(\entries ->
case Dict.size entries of
0 ->
JD.succeed NoPayload
_ ->
JD.fail "Expected empty JSON object"
)
Run Code Online (Sandbox Code Playgroud)
验证:
JD.decodeString emptyJsonDecoder "{}" == Ok NoPayload
JD.decodeString emptyJsonDecoder "{\"a\":123}" == Err "Expected empty JSON object"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
241 次 |
最近记录: |