如何从JSON解码字符串列表?我有这样的代码,目前没有忘记时间:解码字符串列表
import Html exposing (..)
import Html.App as App
import Html.Attributes exposing (..)
import Html.Events exposing (onInput, onClick)
import Http
import Json.Decode as Json exposing ((:=))
import Json.Decode exposing (object3)
import Task
main =
App.program
{ view = view
, init = init
, update = update
, subscriptions = subscriptions
}
init : (Model, Cmd Msg)
init =
(Model "" { productName = "", brand = "", alternateImagePaths = [] }, Cmd.none)
-- MODEL
type alias Product =
{ productName : String
, brand : String
, alternateImagePaths : List String
}
type alias Model =
{ id : String
, product : Product}
-- UPDATE
type Msg
= GetProduct
| UpdateText String
| FetchSucceed Product
| FetchFail Http.Error
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
GetProduct ->
(model, getData model.id)
UpdateText text ->
({ model | id = text }, Cmd.none)
FetchSucceed p ->
({ model | product = p } , Cmd.none)
FetchFail _ ->
({ model | id = "" }, Cmd.none)
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [ type' "text", onInput UpdateText ] []
, button [ type' "button", onClick GetProduct ] [ text "Search" ]
, br [] []
, pre [] [ text model.id ]
, pre [] [ text (toString model.product) ]
]
-- HTTP
getData : String -> Cmd Msg
getData id =
let
url = "https://localhost:3000/v2/product/" ++ id
in
Task.perform FetchFail FetchSucceed (Http.get decodeData url)
decodeData : Json.Decoder Product
decodeData =
object3 Product
("productName" := Json.string)
("brand" := Json.string)
("alternateImagePaths" := Json.list Json.string)
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
如果我删除alternateImagePaths
,它击中FetchSucceed
功能,但如果我离开它,它击中FetchFail
功能。
数据结构(实际响应):
{
"productName": "Men's San Francisco 49ers Design Your Own T-Shirt-",
"team": [
"San Francisco 49ers"
],
"brand": "Pro Line",
"shippingTimeFrame": 3
}
编辑:这显然是发生在你以某种方式得到那个已经不存在的属性。
@ChadGilbert你需要整个JSON对象吗? –
这是实际的json吗?品牌没有尾随逗号,而alternateImagePaths却没有引号 –