Created
March 31, 2018 14:28
-
-
Save neongreen/ca4cb3c9e1b46cf963d48837d98660e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE OverloadedStrings #-} | |
{-# LANGUAGE OverloadedLabels #-} | |
{-# LANGUAGE TypeApplications #-} | |
{-# LANGUAGE TypeOperators #-} | |
{-# LANGUAGE DataKinds #-} | |
import SuperRecord | |
import Data.Aeson | |
import Data.ByteString (ByteString) | |
main = do | |
print $ decodeIntsNewtype sample | |
print $ decodeIntsRecord sample | |
sample :: ByteString | |
sample = "{\"ints\": [1,2,3]}" | |
----------------------------------------------------------- | |
-- With a newtype | |
----------------------------------------------------------- | |
newtype Ints = Ints {ints :: [Int]} | |
instance FromJSON Ints where | |
parseJSON = withObject "ints" $ \o -> | |
Ints <$> o .: "ints" | |
decodeIntsNewtype :: ByteString -> Maybe [Int] | |
decodeIntsNewtype = | |
fmap ints . | |
decodeStrict | |
----------------------------------------------------------- | |
-- With a record | |
----------------------------------------------------------- | |
decodeIntsRecord :: ByteString -> Maybe [Int] | |
decodeIntsRecord = | |
fmap (get #ints) . | |
decodeStrict @(Rec '["ints" := [Int]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment