I have JSON data that may either look like this
{
"items": [Day],
"pageCount": Int,
"totalCount": Int
}
or this
{
"items": [Order],
"pageCount": Int,
"totalCount": Int
}
I've been trying to create a data type for the unvaried fields for use with FromJSON, but I haven't been able to find the proper way to do it, while going through a variety of errors. This is my code in its current state
--{-# LANGUAGE FlexibleInstances #-}
--{-# LANGUAGE MultiParamTypeClasses #-}
--{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson
data Typed = Typed {typeID::Int,name::String} deriving (Show,Eq)
data Day = Day {orderCount::Int,lowPrice::Float,highPrice::Float, avgPrice:: Float,volume::Int,date::String}
data Order = Order {price::Float,isBuy::Bool,location::Typed} deriving (Show,Eq)
data Market a = Market {items::a,pageCount::Int,totalCount::Int} deriving (Show,Eq)
-- Can be either Market [Order] or Market [Day]
instance FromJSON (Market a) where
parseJSON (Object x) = Market <$> x .: "items" <*> x .: "pageCount" <*> x .: "totalCount"
instance FromJSON Order where
parseJSON (Object x) = Order <$> x .: "price" <*> x .: "buy" <*> x .: "location"
instance FromJSON Typed where
parseJSON (Object x) = Typed <$> x .: "id" <*> x .: "name"
instance FromJSON Day where
parseJSON (Object x) = Day <$> x .: "orderCount" <*> x .: "lowPrice" <*> x .: "highPrice"
<*> x .: "avgPrice" <*> x .: "volume" <*> x .: "date"
And this is the current error I get
No instance for (FromJSON a) arising from a use of ‘.:’
Possible fix:
add (FromJSON a) to the context of the instance declaration
In the second argument of ‘(<$>)’, namely ‘x .: "items"’
In the first argument of ‘(<*>)’, namely ‘Market <$> x .: "items"’
In the first argument of ‘(<*>)’, namely
‘Market <$> x .: "items" <*> x .: "pageCount"’