问题描述
所以我需要解码在elm
中包含json array
的json
.这是我的模型:
So I need to decode a json
that contains a json array
in elm
. Here is my model:
type alias ValidationResult =
{ parameter : String
, errorMessage : String
}
type alias ErrorResponse =
{ validationErrors : List ValidationResult }
这是json
的示例:
{"ValidationErrors": [{"Parameter": "param1","ErrorMessage": "message 1"},{"Parameter": "param2","ErrorMessage": "error message 2"}]}
我试图创建一个ValidationResult
解码器,例如:
I've tried to create a ValidationResult
decoder, like:
decodeValidationResults : Decoder ValidationResult
decodeValidationResults =
map2 ValidationResult
(at [ "Parameter" ] Json.Decode.string)
(at [ "ErrorMessage" ] Json.Decode.string)
但是我不知道该怎么做.
But I don't know how to proceed further.
我正在使用elm
0.18
I am using elm
0.18
推荐答案
您快到了!您只需要一个解码器即可解码ErrorResponse
类型.为此,请创建另一个解码器,该解码器使用您已经创建的解码器列表,并假设字段名称为"ValidationErrors"
:
You are almost there! You just need a decoder that decodes the ErrorResponse
type. To do so, create another decoder that uses a list of the decoder you've already created, assuming the field name is "ValidationErrors"
:
import Json.Decode exposing (..)
decodeErrorResponse : Decoder ErrorResponse
decodeErrorResponse =
map ErrorResponse
(field "ValidationErrors" (list decodeValidationResults))
一点建议:只有一个级别时,可以使用Json.Decode.field
代替Json.Decode.at
.您可以这样重写decodeValidationResults
:
One bit of advice: You can use Json.Decode.field
instead of Json.Decode.at
when there is only a single level. You can rewrite decodeValidationResults
as this:
decodeValidationResults : Decoder ValidationResult
decodeValidationResults =
map2 ValidationResult
(field "Parameter" string)
(field "ErrorMessage" string)
这篇关于elm:解码包含json数组的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!