If I have JSON
and I try to derive the FromJSON
instances automatically with Generics
, I run into problems with id
existing in more than one place in the JSON
.
Is there a way for me to override just the id
part or do I have to write the whole instance in order to change those particular entries? The JSON
actually has more fields, but I have left most of it out in this example. So it is actually rather tedious to write out the whole FromJSON
instance.
JSON:
{
"response": [
{
"id": 1,
"brandId": 1,
"productTypeId": 1,
"identity": {
"sku": "x",
"barcode": "Ax"
},
"stock": {
"stockTracked": false,
"weight": {
"magnitude": 0
},
"dimensions": {
"length": 0,
"height": 0,
"width": 0,
"volume": 0
}
},
"financialDetails": {
"taxable": false,
"taxCode": {
"id": 1,
"code": "x"
}
},
... etc
]
}
CODE So far:
data Response = Response
{ response :: [Body]
} deriving (Show,Generic)
data Body = Body
{ id :: Int
, brandId :: Int
, productTypeId :: Int
, identity :: Identity
, productGroupId :: Int
, stock :: Stock
, financialDetails :: FinancialDetails
} deriving (Show,Generic)
data Identity = Identity
{ sku :: String
, ean :: String
, barcode :: String
} deriving (Show,Generic)
data Stock = Stock
{ stockTracked :: Bool
, weight :: Weight
, dimensions :: Dimensions
} deriving (Show,Generic)
data Weight = Weight
{ magnitude :: Int
} deriving (Show,Generic)
data Dimensions = Dimensions
{ length :: Int
, height :: Int
, width :: Int
, volume :: Int
} deriving (Show,Generic)
data FinancialDetails = FinancialDetails
{ taxable :: Bool
, taxCode :: TaxCode
} deriving (Show,Generic)
data TaxCode = TaxCode
{ id :: Int
, code :: String
} deriving (Show,Generic)
instance FromJSON Response
instance FromJSON Body
instance FromJSON Identity
instance FromJSON Stock
instance FromJSON Weight
instance FromJSON Dimensions
instance FromJSON FinancialDetails
This gives the error:
[1 of 1] Compiling Main ( reponse.hs, interpreted )
response.hs:73:8:
Multiple declarations of `id'
Declared at: response.hs:19:7
response.hs:73:8
Failed, modules loaded: none.
Ideally I would like to change the first id
to body_id
and the second to taxCode_id
without having to write out the whole instance.