如何从http响应解析json数据

时间:2019-07-15 05:31:09

标签: json http decode elm

我正在尝试从HTTP响应中解析Json数据。 但是会发生错误。 您如何从HTTP响应中解析Json数据?

Json数据如下。

[
    {
        "id": 1,
        "name": "sample name",",
        "articles": [
            {
                "ID": 1,
                "Title": "sample title",
                "Description": "sample description",
            },
            {
                "ID": 2,
                "Title": "sample title",
                "Description": "sample description",
            },
            {
                "ID": 3,
                "Title": "sample title",
                "Description": "sample description",
            }
        ]
    },
    {
        "id": 2,
        "name": "sample name",
        "articles": [
            {
                "ID": 4,
                "Title": "sample title",
                "Description": "sample description",
            }
        ]
    },
    {
        "id": 3,
        "name": "sample name",
        "articles": [
            {
                "ID": 5,
                "Title": "sample title",
                "Description": "sample description",
            },
            {
                "ID": 6,
                "Title": "sample title",
                "Description": "sample description",
            },
            {
                "ID": 7,
                "Title": "sample title",
                "Description": "sample description",
            }
        ]
    }
]

这就是我在代码中得到的。

-- HTTP


type alias Tag = 
    { name: String
    }


getTag : Cmd Msg
getTag =
    Http.get
        { url = "http://sample.com/tags"
        , expect = Http.expectJson GotTag listDecoder
        }


listDecoder : Decoder (List Tag)
listDecoder =
    JD.list tagDecoder


tagDecoder: Decoder Tag
tagDecoder =
  JD.map Tag
    (field "name" string)

但是出现错误消息。

TYPE MISMATCH - The 2nd argument to `expectJson` is not what I expect:

119|         , expect = Http.expectJson GotGif listDecoder
                                               #^^^^^^^^^^^#
This `listDecoder` value is a:

    Decoder #(List Tag)#

But `expectJson` needs the 2nd argument to be:

    Decoder #String#

#Hint#: I always figure out the argument types from left to right. If an argument
is acceptable, I assume it is “correct” and move on. So the problem may actually
be in one of the previous arguments!

我知道整个Json数据都是列表。 因此,我尝试先解码列表。

但是错误消息指出expectJson需要第二个参数为:Decoder #String#。

我在这里想要的不是String数据。我要清单。

0 个答案:

没有答案