Created
April 12, 2025 13:21
-
-
Save mizchi/36b6f2d9f5266cb872a8abe5b11937dd to your computer and use it in GitHub Desktop.
This file contains 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 ScopedTypeVariables #-} | |
{-# LANGUAGE DeriveGeneric #-} -- FromJSON と Show の自動導出に必要 | |
module Main (main) where | |
import qualified Network.HTTP.Req as Req | |
import qualified Data.Aeson as Aeson | |
import Control.Monad.IO.Class (liftIO) | |
import GHC.Generics (Generic) -- DeriveGeneric に必要 | |
import Data.Text (Text) -- Todo 型の title フィールドで使用 | |
-- JSON 構造に対応するレコード型 | |
data Todo = Todo | |
{ userId :: Int | |
, id :: Int | |
, title :: Text -- JSON の文字列は Text 型で扱うのが一般的 | |
, completed :: Bool | |
} deriving (Generic, Show) -- Generic と Show を自動導出 | |
-- FromJSON インスタンスを自動導出 | |
-- これにより Aeson が JSON から Todo 型へ変換する方法を理解する | |
instance Aeson.FromJSON Todo | |
main :: IO () | |
main = Req.runReq Req.defaultHttpConfig $ do | |
-- レスポンスボディを Todo 型としてパースする | |
response <- Req.req Req.GET | |
(Req.https "jsonplaceholder.typicode.com" Req./: "todos" Req./: "1") | |
Req.NoReqBody | |
Req.jsonResponse -- 型推論により Todo 型を期待する | |
mempty | |
-- パースされた Todo 型のボディを取得 | |
let todo :: Todo = Req.responseBody response | |
-- 結果 (Todo 型) をコンソールに出力 (Show インスタンスが使われる) | |
liftIO $ print todo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment