2016-03-04 77 views
0

我有以下型號:耶索德 - 埃宋, 「期待的Int64時,遇到字符串代替」

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

大概'ProductTaxRateId'是'Int64'但你提供' 「ID」: 「1」',而不是' 「ID」:1' – mb21

+0

@ MB21是的......但我不想要更改json(我遵循標準),我只想做一個轉換 – FtheBuilder

+3

@FtheBuilder你可以(低效地)使用'readMaybe :: String - > Maybe Int64'解析字符串。 –

回答

1

我找到了一種方法來做到這一點,這很簡單,我剛剛使用了fromPathPiece

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