実践Haskell Aesonを使ったJSONデータの処理 データ型をFromJSONとToJSONのインスタンスにする 簡単な方法 encode関数、decode関数、言語拡張、LANGUAGEプラグマ、DeriveGeneric、Generic、レコード構文
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT7(実践Haskell)、LESSON 40(Aesonを使ったJSONデータの処理)、40.3(データ型をFromJSONとToJSONのインスタンスにする)、簡単な方法のクイックチェック 40-2の解答を求めてみる。
コード
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics ( Generic )
import qualified Data.Text as T
import qualified Data.ByteString.Lazy as BC
import qualified Language.Haskell.TH.Syntax as BC
import Data.Aeson (FromJSON, ToJSON, encode, decode)
data Name = Name {firstName :: T.Text
, lastName :: T.Text} deriving (Show, Generic)
instance ToJSON Name
instance FromJSON Name
name :: Name
name = Name {firstName = "Haskell", lastName = "GHC"}
nameJSON :: BC.ByteString
nameJSON = encode name
nameFromJSON :: Maybe Name
nameFromJSON = decode nameJSON
wrongJSON :: BC.ByteString
wrongJSON = "{\"first\":\"Haskell\",\"last\":\"GHC\"}"
nameFromWrongJSON :: Maybe Name
nameFromWrongJSON = decode wrongJSON
main :: IO ()
main = do
print "Just"
print name
print nameJSON
print nameFromJSON
print "Nothing"
print wrongJSON
print nameFromWrongJSON
入出力結果(Terminal, Zsh)
% runghc sample02.hs
"Just"
Name {firstName = "Haskell", lastName = "GHC"}
"{\"firstName\":\"Haskell\",\"lastName\":\"GHC\"}"
Just (Name {firstName = "Haskell", lastName = "GHC"})
"Nothing"
"{\"first\":\"Haskell\",\"last\":\"GHC\"}"
Nothing
%