Yesod - Aeson,"当期待Int64时,遇到String而不是#34;

时间:2016-03-04 19:44:56

标签: haskell yesod aeson

我有以下型号:

Conf
  productTaxRateId ProductTaxRateId Maybe
  barCodeLength Int

我已将以下json发送到服务器:

{
  "attributes": {
    "barCodeLength":25
  },
  "relationships": {
    "productTaxRate": {
      "data": {
        "id": "1",
        "type": "ProductTaxRate"
      }
    }
  },
 "id": "1",
 "type": "Conf"
}

以下是我的FromJSON

instance FromJSON Conf where
  parseJSON (Object o) = Conf 
      <$> ((o .: "relationships") >>= (.: "productTaxRate") >>= (.: "data") >>= (.: "id"))
      <*> ((o .: "attributes") >>= (.: "barCodeLength"))
  parseJSON _ = mzero

但是我的请求中出现以下错误:

{"message":"Invalid Arguments","errors":["when expecting a Int64, encountered String instead"]}

如何正确进行转换?

提前感谢您,HaskellYesod非常出色。

1 个答案:

答案 0 :(得分:1)

我找到了一种方法来做到这一点,这很简单,我只是使用了fromPathPiece

instance FromJSON Conf where
  parseJSON (Object o) = Conf 
      <$> fmap fromPathPiece ((o .: "relationships") >>= (.: "productTaxRate") >>= (.: "data") >>= (.: "id"))
      <*> ((o .: "attributes") >>= (.: "barCodeLength"))
  parseJSON _ = mzero