在Elm中,如何在嵌套JSON中解码JSON对象

问题描述 投票:0回答:1

我使用Elm 0.19.1和NoRedInk / elm-json-decode-pipeline / 1.0.0

我的飞机类型是

type alias Aircraft = {name:String}

为此,我有以下解码器:

aircraftDecoder : Json.Decode.Decoder Aircraft        
aircraftDecoder =            
    Json.Decode.succeed Aircraft            
    |> Json.Decode.Pipeline.required "name" Json.Decode.string

不幸的是,解码器抱怨我说:“ BadBody”给定值的问题:(...)“这是因为实际上我感兴趣的区域周围充满了噪音(来自HATEOAS api),就像这样:

{
  "_embedded" : {
    "aircrafts" : [ {
      "name" : "AC01",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/aircrafts/1"
        },
        "aircraft" : {
          "href" : "http://localhost:8080/aircrafts/1"
        }
      }
    }, {
      "name" : "AC01",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/aircrafts/2"
        },
        "aircraft" : {
          "href" : "http://localhost:8080/aircrafts/2"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/aircrafts{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/aircrafts"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 4,
    "totalPages" : 1,
    "number" : 0
  }
}

如何更改代码,并保持使用管道,以使解码器不会因所有这些噪声而丢失?

我听说过有关使用Json.Decode.at的一些信息,但文档不足以让我获得正确的代码。

json pipeline elm hateoas decoder
1个回答
0
投票

以下应该起作用:

aircraftNameDecoder : Json.Decode.Decoder String
aircraftNameDecoder =
    Json.Decode.map (Maybe.withDefault "" << List.head) <|
        Json.Decode.at [ "_embedded", "aircrafts" ] <|
            Json.Decode.list (Json.Decode.field "name" Json.Decode.string)


aircraftDecoder : Json.Decode.Decoder Aircraft
aircraftDecoder =
    Json.Decode.succeed Aircraft
        |> Json.Decode.Pipeline.custom aircraftNameDecoder
© www.soinside.com 2019 - 2024. All rights reserved.